以下作品:
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/