将数据框作为函数参数传递,但在调用函数时将其名称用作字符串

Passing a data frame as a function argument, but using its name as a string in the call to the function

我有一个 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