mathlete
mathlete

Reputation: 6682

Evaluate an expression given as a string inside substitute()

I would like to evaluate an expression given as a string inside substitute(), but I don't get the expected output (an x-axis label "My index"... with the subscript):

mystrng <- "index[1]" # string
plot(0~1, xlab = substitute("My"~ind, list(ind = mystrng))) 
plot(0~1, xlab = substitute("My"~ind, list(ind = parse(text = mystrng))))
plot(0~1, xlab = eval(substitute("My"~ind, list(ind = parse(text = mystrng)))))

Note:

1) Without substitute(), one can work with parse(text = mystrng). See also here. As this link also reveals, one should not work with strings, but, e.g., quote(index[1]) which works with the first plot() call above. I'm just interested in how one would go about strings.

2) The last plot() call trial was inspired by ?substitute

3) Ideally the solution would also work if mystrng contains blanks, like "My index[1]"

Upvotes: 1

Views: 42

Answers (1)

user2554330
user2554330

Reputation: 44788

parse() returns an expression, which is essentially a list of language objects marked as a different type. You want to put a language object into the title, so I think this is what you want:

plot(0~1, xlab = substitute("My"~ind, list(ind = parse(text = mystrng)[[1]])))

That gives this as the x label:

enter image description here

This won't work if mystrng isn't legal R syntax, so "My index[1]" will need some preprocessing to convert it to something legal like "My~index[1]"

Upvotes: 1

Related Questions