【问题标题】:using parse(text= )使用解析(文本=)
【发布时间】:2021-03-14 19:04:14
【问题描述】:

我以为我理解了 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]] 

谢谢。

【问题讨论】:

    标签: r parsing expression


    【解决方案1】:

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

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

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

    do.call('ggarrange', list_of_plots)
    

    【讨论】:

    • 感谢 do.call 的建议。 ggarrange 的参数是如何输入的?这是对 ggarrange 的调用: ggarrange( emo_plot + rremove("x.text"), labels = c("A", "B", "C", "D"),ncol = 2, nrow = 6)
    • do.call('ggarrange', emo_plot) 有效,但我看不到如何设置列号和行号。
    • 我在这里看到了答案stackoverflow.com/questions/57810140/…
    猜你喜欢
    • 2016-05-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-09
    • 2018-10-27
    • 2012-12-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多