r - 如何在 R 中使用字符串作为代码

标签 r

以下作品:

plot(Sepal.Length ~ Petal.Width, data = iris)
abline(lm(Sepal.Length ~ Petal.Width, data = iris))

但是下面的代码不起作用:

str = "Sepal.Length ~ Petal.Width, data = iris"
plot(str)
abline(lm(str))

我尝试了 deparse(substitute)、as.forumla 和 eval,但它们不起作用。

最佳答案

使用问题中的 str 试试这个:

 # fun and args should each be a character string
 run <- function(fun, args) eval(parse(text = sprintf("%s(%s)", fun, args)))

 run("plot", str)
 abline(run("lm", str))

或者试试这个:

 `%(%` <- function(fun, args) run(deparse(substitute(fun)), args)
 plot %(% str
 abline(lm %(% str)

请注意,这种方法可以处理参数中有逗号(而不是参数分隔符)并且不使用任何外部包的情况。

关于r - 如何在 R 中使用字符串作为代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26699588/

相关文章:

r - 使用 dplyr : object ‘data_frame’ is not exported by 'namespace:vctrs' 时出错

r - 为模型选择实现 LOOCV(不使用 caret 包)

r - 在 ggplot2 控制图上显示 2 个标准差(除了正常的 3 个)

r - 如何将 RMSE、斜率、截距、r^2 添加到 R 图中?

r - R中间隔不均匀的多个文件的分箱

r - 绘制 R 地区粮农组织捕鱼区 map

r - 增加矩阵打印输出的宽度

r - 基于连续值的组变量

R将特定行和列乘以常数

r - 在矩阵中查找子矩阵