-3

Suppose I have a character string of a subsetted object name. For example:

foo$var1[foo$var2 < 10 & foo$var3 %in% c(0:100)]  #is currently represented as...
"foo$var1[foo$var2 < 10 & foo$var3 %in% c(0:100)]"

I want to call the subsetted object using the character string of the object's name.

I tried using get():

get("foo$var1[foo$var2 < 10 & foo$var3 %in% c(0:100)]")

but I get the error:

Error in "foo$var1[foo$var2 < 10 & foo$var3 %in% c(0:100)]":
object  "foo$var1[foo$var2 < 10 & foo$var3 %in% c(0:100)]" not found

I'm assuming there is a way to do this using subsetted objects (vs. just an object name, which I know works).

Thanks in advance!

1
  • 7
    How did you get yourself in this situation? Putting R code into strings isn't something one might consider a good strategy in R. The get() functions returns variables of a given name, it does not evaluate code (and operations like [ and & and < are functions in R). You might be able to parse and eval, eval(parse(text=x)), but that's not something I would recommend necessarily. Commented Jul 27, 2015 at 19:22

1 Answer 1

5

As mentioned in comments by @MrFlick, you can do this:

eval(parse(text="foo$var1[foo$var2 < 10 & foo$var3 %in% c(0:100)]"))

parse turns the string into an expression and eval evaluates that expression.

Though, this is commonly considered a bad practice in R see here

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

2 Comments

fortunes::fortune(106)
@DavidArenburg Thanks for editing! I should have read the comments more carefully.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.