1

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"?

daniellga
  • 1,142
  • 6
  • 16

1 Answers1

2

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
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213