Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/arduino/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在R中使用字符串作为代码_R - Fatal编程技术网

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

如何在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(替代品),如.forumla和eval,但它们不起作用。使用问题中的str尝试以下方法:

以下工作:

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(替代品),如.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)
#fun和args都应该是字符串

运行尝试分析参数并创建它们:

fun_str<- function(fun, str_arg){
    ## split args separted by comma
    m <- as.list(strsplit(str_arg,',')[[1]])
    args  <- lapply(m,function(x){
      ## remove any extra space 
      arg = str_trim(strsplit(x,'=')[[1]])
      if (arg[1]=="data") get(arg[2],parent.frame())
      else if (grepl('~',x))  as.formula(x)
    })
    do.call(fun,args)
}

这是另一种选择。您可以使用
调用
对象来表示
数据
参数,然后在参数列表中对其求值

f <- formula("Sepal.Length ~ Petal.Width")
cl <- call("=", "data", iris)
plot(f, eval(cl))
abline(lm(f, eval(cl)))

您可以执行类似于
str=“Sepal.Length~Petal.Width”的操作;绘图(如公式(str),数据=iris);abline(lm(str,iris))
。虽然这不完全是你想要的,但是“data=iris”也可以包含在代码中?可能可以使用一些非常讨厌的
解析
/
解压
/
引用
/
..
组合。或者使用一些外部软件包,但我可能错了,谢谢大家的回答。这个问题确实引起了一些天才的兴趣。如果参数中有逗号,则会出现问题,例如,如果
main=“Sepal.Length,Sepal.Length”
是字符串的一部分。
f <- formula("Sepal.Length ~ Petal.Width")
cl <- call("=", "data", iris)
plot(f, eval(cl))
abline(lm(f, eval(cl)))
str <- "Sepal.Length ~ Petal.Width, data = iris"
s <- strsplit(str, ", data = ")[[1]]
with(setNames(as.list(s), c("formula", "data")), {
    getd <- get(data, parent.frame())
    plot(f <- formula(formula), data = getd)
    abline(lm(f, data = getd))
})