我想创建一个函数“startswith”以在 data.table 中的括号内使用。它应该返回一个字符向量,其中包含以提供的字符开头的列名称。例如
DT <- data.table(x=1, y=2, z1=1, z2=2)
# the syntax DT[, startswith("z")] is equivalent to
DT[, .(z1, z2)]
# returns
z1 z2
1: 1 2
我熟悉 grep 来搜索文本表达式,但无法找到从括号内引用 DT 列名称的方法。我尝试的一个解决方案是使用 ls() 和与 DT 关联的环境来列出 DT 中的所有列,但我还没有找到一种从括号内引用此环境的方法。
目标是为 grep 创建一个包装器以用作便利函数。我不想在括号内指定 DT。
最佳答案
当然有一种更惯用的方法,但这就是我想出的:
startswith <- function(pattern = "z") {
re <- paste0("^", pattern)
call_info <- deparse(sys.calls()[[1]])
if (grepl("(^.+\\()(.+)(\\)$)",call_info)) {
this_name <- sub("(^.+\\()(.+)(\\)$)","\\2",call_info)
} else {
this_name <- strsplit(call_info,"\\[")[[1]][1]
}
this <- copy(get(this_name))
this_names <- names(this)
eval.parent(grep(re,this_names))
}
<小时/>
library(data.table)
DT <- data.table(x=1, y=2, z1=1, z2=2)
##
R> DT[,.(z1, z2)]
z1 z2
1: 1 2
##
R> DT[,startswith(), with=F]
z1 z2
1: 1 2
<小时/>
我必须添加 if () {} else {}
block ,以便可以在函数内部使用它,例如
Foo <- function(gt) {
f <- gt[,startswith(),with=F]
# {do something interesting with f}
f
}
##
R> Foo(DT)
z1 z2
1: 1 2
<小时/>
我认为这是一个有趣的问题 - 据我所知,R 没有像 the this
pointer in C++ 这样的概念。 ,但在这种情况下它肯定很有用。本质上,我所有的 sys.call
、get
等黑客技术都是为了检索调用对象的名称。
关于regex - 从括号内引用 data.table 列名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29435337/