【问题标题】:Passing a data frame as a function argument, but using its name as a string in the call to the function [duplicate]将数据框作为函数参数传递,但在调用函数时使用其名称作为字符串 [重复]
【发布时间】:2020-07-10 06:50:49
【问题描述】:

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

【问题讨论】:

    标签: r rlang


    【解决方案1】:

    您可以在函数中使用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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-04
      • 1970-01-01
      • 2019-05-10
      • 2020-05-01
      • 1970-01-01
      相关资源
      最近更新 更多