Search code examples
rrlang

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


I have a data.table, a string with its name and a function:

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)]
}

When calling the function using the data.table as its argument, everything is ok.

> fun(example_dt)
[1] "example_dt"
   a b
1: 1 4
2: 2 5

Calling with the string doesn't work, of course.

> fun(string)
[1] "string"
Error in x[c(1, 2), c(1, 2)] : número incorreto de dimensões

I can overcome this problem using get, but then I lose information about the name of the data.table.

> fun(get(string))
[1] "get(string)"
   a b
1: 1 4
2: 2 5

Any idea of how can I call the function using the string and, at the same time, retrieve the data.table's original name "example_dt"?


Solution

  • You can use get in the function specifying the environment from where it is called.

    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