我有一个data.table,一个带名称的字符串和一个函数:
example_dt <- data.table(a = c(1,2,3), b = c(4,5,6))
string <- 'example_dt'
fun <- function(x) {
print((deparse(substitute(x))))
x[c(1,2), c(1,2)]
}
当使用data.table作为参数调用该函数时,一切正常。
> fun(example_dt)
[1] "example_dt"
a b
1: 1 4
2: 2 5
当然,用字符串调用是行不通的。
> fun(string)
[1] "string"
Error in x[c(1, 2), c(1, 2)] : número incorreto de dimensões
我可以使用get克服此问题,但是随后我丢失了有关data.table名称的信息。
> fun(get(string))
[1] "get(string)"
a b
1: 1 4
2: 2 5
是否知道如何使用字符串调用该函数,同时检索data.table的原始名称“ example_dt”?
您可以get
在函数中使用它来指定从中调用环境。
fun <- function(x) {
print(x)
get(x,envir = parent.frame())[c(1,2), c(1,2)]
#OR
#get(x,envir = .GlobalEnv)[c(1,2), c(1,2)]
}
fun(string)
#[1] "example_dt"
# a b
#1: 1 4
#2: 2 5
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句