3

I have 2 variables, and a list. I want to use the two variables to access to the list files, but I don´t know how to deal with it.

Imagien that I have this:

data <- list()
data$one <- "first"

And that I have 2 variables, var1, and var2:

var1 <- "data"
var2 <- "one"

How can I use this variables to access to data$one?

I have tried with:

get(paste0(var1,"$",var2))

But I get an error:

Error in get(paste0(var1,"$",var2)): object data$one not found 
jff
  • 300
  • 3
  • 14
  • 2
    Possible duplicate of [Access variable value where the name of variable is stored in a string](https://stackoverflow.com/questions/3971844/access-variable-value-where-the-name-of-variable-is-stored-in-a-string) – markus Nov 30 '18 at 12:24
  • `get(var1)[[var2]]` – markus Nov 30 '18 at 12:24

1 Answers1

2

As @markus pointed out,

get(var1)[[var2]]
# [1] "first"

works as needed.

I guess what's equally important is why your approach didn't work. While

paste0(var1,"$",var2)
# [1] "data$one"

correctly describes what you are interested in, data$one itself is not a variable, it's a result of a function call, which can also be written as:

`$`(data, one)
# [1] "first"

Now it somewhat makes sense that something like

get("`$`(data, one)")
# Error in get("`$`(data, one)") : object '`$`(data, one)' not found

shouldn't work, just like

get("2 + 2")
# Error in get("2 + 2") : object '2 + 2' not found
Julius Vainora
  • 47,421
  • 9
  • 90
  • 102