Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/wix/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/xpath/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 将数据帧作为函数参数传递,但在函数调用中使用其名称作为字符串_R_Rlang - Fatal编程技术网

R 将数据帧作为函数参数传递,但在函数调用中使用其名称作为字符串

R 将数据帧作为函数参数传递,但在函数调用中使用其名称作为字符串,r,rlang,R,Rlang,我有一个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)] } 当然,用字符串调用不起作用 > fun(string) [1] "string" Er

我有一个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)]
}
当然,用字符串调用不起作用

> 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

是否知道如何使用字符串调用函数,同时检索数据。表的原始名称“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
有趣
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