1

Is it possible to dynamically convert strings into object references? Suppose we have:

a <- 5
b <- 6

letters <- c("a", "b")

eval(parse(text = "a")) returns the value for a, or 5. Is it possible to have the values for multiple strings returned? When I include multiple strings in parse only the last value is returned.

>eval(parse(text = letters))
[1] 6

The desired output is a vector or values for the inputted strings:

[1] 5 6
Bjørn Kallerud
  • 979
  • 8
  • 23
  • Seems like a duplicate; there are several existing questions on using `mget()` with vectors of strings, including with [dplyr](https://stackoverflow.com/questions/50013141/how-can-i-pass-a-vector-as-variable-arguments-into-a-function-in-r) and [data.table](https://stackoverflow.com/questions/23584346/supply-arguments-to-data-table-as-1-vector-of-strings-and-2-variablenames). Ultimately your intent is to parameterize which objects you pass into function calls, right? It is possible to avoid writing this sort of code. – smci Sep 05 '19 at 00:14
  • Possible duplicate of [How to parametrize function calls in dplyr 0.7?](https://stackoverflow.com/questions/43415475/how-to-parametrize-function-calls-in-dplyr-0-7) – smci Sep 05 '19 at 00:20
  • Generally noone should ever need to write code like this, any time you find yourself doing it it's a code smell you're not using your library right. Based on your other questions it seems like you're constructing calls to dplyr for Shiny. – smci Sep 05 '19 at 00:21

1 Answers1

1

Here, we can use mget to return the values of the objects in a list and then unlist the list output

unlist(mget(letters), use.names = FALSE)
#[1] 5 6

Also, if we are using eval(parse, it works only for a single element, so loop through the 'letters' and then do eval(parse

unname(sapply(letters, function(x) eval(parse(text = x))))
#[1] 5 6

However, the recommended option would be mget


letters/LETTERS are inbuilt Constants to return the lower/upper case letters. So, it is better not to use identifier names with reserve words or function names

akrun
  • 874,273
  • 37
  • 540
  • 662