Reputation: 9
I thought I understood eval(parse(text = )) but I am getting an error. I have a string named plotString that has been constructed using a for loop. If I print it out, it looks like this:
plotString
[1] "emo_plot[[1]],sentiment_plot[[1]],emo_plot[[2]],sentiment_plot[[2]],emo_plot[[3]],sentiment_plot[[3]],emo_plot[[4]],sentiment_plot[[4]],emo_plot[[5]],sentiment_plot[[5]],emo_plot[[6]],sentiment_plot[[6]],emo_plot[[7]],sentiment_plot[[7]],emo_plot[[8]],sentiment_plot[[8]],emo_plot[[9]],sentiment_plot[[9]],emo_plot[[10]],sentiment_plot[[10]]"
The end goal is to put it as the first argument in
pairPlot <- ggarrange( eval(parse(text=plotString)) + rremove("x.text"), labels = c("A", "B", "C", "D"), ncol = 6, nrow = 4)
But simply running it in
parse(text=plotString)
gives this error
Error in parse(text = plotString) : <text>:1:14: unexpected ','
1: emo_plot[[1]],
^
and this
eval(parse(text=plotString))
gives, of course, the same
Error in parse(text = plotString) : <text>:1:14: unexpected ','
1: emo_plot[[1]],
^
and this
pairPlot <- ggarrange( eval(parse(text=plotString)) + rremove("x.text"), labels = c("A", "B", "C", "D"), ncol = 6, nrow = 4)
gives, of course, the same
Error in parse(text = plotString) : <text>:1:14: unexpected ','
1: emo_plot[[1]],
^
I have read that the text needs to evaluate to an R expression and I guess plotString is not an R expression. If that is the issue, how can I get the entry before the plus(+) sign in ggarrange() to be something like
emo_plot[[1]],sentiment_plot[[1]],emo_plot[[2]],sentiment_plot[[2]]
Thank you.
Upvotes: 0
Views: 363
Reputation: 545588
parse()
parses full expressions. That is, the code that you pass it must be syntactically valid self-contained R code. You can’t pass it fragments. Even if you could do that, you can’t eval()
fragments either; once again, the expression you pass to eval()
must be self-contained, complete, valid R code.
I’d generally be wary of any use of eval(parse(…))
in code; it’s usually solving the wrong problem.
In your case, where are you getting the input from? Unless the data comes from outside R, it’s almost certainly a better solution to store and manipulate the data as a list of expressions, not as a string. Then you can use it via do.call()
:
do.call('ggarrange', list_of_plots)
Upvotes: 1