r - 使用解析(文本=)
问题描述
我以为我理解了 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]]
谢谢你。
解决方案
parse()
解析完整的表达式。也就是说,您传递给它的代码必须是语法上有效的自包含 R 代码。你不能传递它的碎片。即使你能做到,你也不能eval()
分片;再一次,您传递给的表达式eval()
必须是独立的、完整的、有效的 R 代码。
我通常会警惕eval(parse(…))
代码中的任何使用;它通常解决了错误的问题。
就您而言,您从哪里获得输入?除非数据来自 R 外部,否则将数据存储和操作为表达式列表而不是字符串几乎肯定是更好的解决方案。然后您可以通过以下方式使用它do.call()
:
do.call('ggarrange', list_of_plots)
推荐阅读
- javascript - 用户填写“用户名”字段后如何打印用户名?为什么它会消失?
- html - 未知的 HTML 日期格式“1615856400000”=“2021 年 3 月 16 日,星期四”,“1615770000”=“2021 年 3 月 15 日,星期四”等
- react-dom - 使用 reactdom 在 React 中渲染组件时出现问题
- r - if 语句在 r 中有多个条件?
- javascript - 无法在日文键盘布局中使用条形码发布 html 表单
- jsf - 如何使用 PrimeFaces 将 pe:badge 添加到 bean 中动态创建的菜单
- metafor - 一个不寻常的荟萃分析:使用 1 的样本量?
- javascript - 如何从一个变量中的对象调用多个键
- react-testing-library - React 测试库:如何在不删除自动清理的情况下显式重用渲染的组件
- javascript - React-Native / Expo 项目中的“无法连接到 Metro 服务器”