首页 > 解决方案 > 使用解析(文本=)

问题描述

我以为我理解了 eval(parse(text = )) 但我得到了一个错误。我有一个名为 plotString 的字符串,它是使用 for 循环构造的。如果我打印出来,它看起来像这样:

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]]"

最终目标是将其作为第一个参数

pairPlot <- ggarrange( eval(parse(text=plotString)) + rremove("x.text"), labels = c("A", "B", "C", "D"), ncol = 6, nrow = 4)

但只需运行它

parse(text=plotString)

给出这个错误

Error in parse(text = plotString) : <text>:1:14: unexpected ','
1: emo_plot[[1]],
                 ^

和这个

eval(parse(text=plotString))

当然,给出相同的

Error in parse(text = plotString) : <text>:1:14: unexpected ','
1: emo_plot[[1]],
                 ^

和这个

pairPlot <- ggarrange( eval(parse(text=plotString)) + rremove("x.text"), labels = c("A", "B", "C", "D"), ncol = 6, nrow = 4)

当然,给出相同的

Error in parse(text = plotString) : <text>:1:14: unexpected ','
1: emo_plot[[1]],
                 ^

我读过文本需要评估为 R 表达式,我猜 plotString 不是 R 表达式。如果这是问题所在,我怎样才能让 ggarrange() 中的加号(+)之前的条目类似于

emo_plot[[1]],sentiment_plot[[1]],emo_plot[[2]],sentiment_plot[[2]] 

谢谢你。

标签: rparsingexpression

解决方案


parse()解析完整的表达式。也就是说,您传递给它的代码必须是语法上有效的自包含 R 代码。你不能传递它的碎片。即使你能做到,你也不能eval()分片;再一次,您传递给的表达式eval()必须是独立的、完整的、有效的 R 代码。

我通常会警惕eval(parse(…))代码中的任何使用;它通常解决了错误的问题。

就您而言,您从哪里获得输入?除非数据来自 R 外部,否则将数据存储和操作为表达式列表而不是字符串几乎肯定是更好的解决方案。然后您可以通过以下方式使用它do.call()

do.call('ggarrange', list_of_plots)

推荐阅读