Reputation: 99
I have three variables which I want to call from a vector containing variable names produced by concatenating the string "variable." with the suffix "ONE", "TWO" and "THREE", as per code below:
variable.ONE <- 1
variable.TWO <- 2
variable.THREE <- 3
j <- c("ONE","TWO","THREE")
variables <- paste0("variable.",j)
"Variables" prints:
variables
[1] "variable.ONE" "variable.TWO" "variable.THREE"
I am looking for a way to return the values of all three variables contained in the vector "variables", hence:
[1] 1 2 3
However, calling the variables contained in "variables" does not work as intended:
get(variables)
produces:
[1] 1
eval(noquote(variables)))
produces:
[1] variable.ONE variable.TWO variable.THREE
eval(as.name(variables)))
produces:
[1] 1
These attempts are only three of many, none of which brought me to the desired - and simple - output of:
[1] 1 2 3
Therefore, I would greatly appreciate any help you may be able to offer!
Thanks in advance!
Upvotes: 4
Views: 74
Reputation: 2311
You can use mget(variables)
for a character vector, returning a list of objects.
Note that there is no way to ensure that each element of variables
refers to an atomic object of the same type (e.g., what if variable.TWO <- "b"
?), so it is expected that the result should be a list instead of a vector.
You can achieve your desired output with unlist(mget(variables))
.
Upvotes: 4