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
3
  • Seems like a duplicate; there are several existing questions on using mget() with vectors of strings, including with dplyr and data.table. Ultimately your intent is to parameterize which objects you pass into function calls, right? It is possible to avoid writing this sort of code. Commented Sep 5, 2019 at 0:14
  • Possible duplicate of How to parametrize function calls in dplyr 0.7? Commented Sep 5, 2019 at 0: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. Commented Sep 5, 2019 at 0:21

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.