2014-11-02 18 views
2

以下工作:如何在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(替補),as.forumla和eval,但他們做的不行。

+0

你可以做一些像'str =「Sepal.Length〜Petal.Width」; (as.formula(str),data = iris); abbr(lm(str,iris))'。雖然它不完全是你想要的 – 2014-11-02 13:07:25

+0

'data = iris'是否也包含在代碼中? – rnso 2014-11-02 13:11:34

+0

大概可以使用一些非常討厭的'parse' /'deparse' /'quote' /'...'組合。或者使用一些外部軟件包,但我可能在這裏錯了 – 2014-11-02 13:13:15

回答

2

從問題中使用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) 

注意,這種方法可以處理那裏有逗號的參數(相對於參數的情況分隔符),並且不使用任何外部軟件包。

2

嘗試解析參數,並創建它們:

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) 
} 

然後調用它:

fun_str("plot",str) 
fun_str("lm",str) 
+0

如果在參數中有一個逗號,例如有問題如果'main =「Sepal.Length,Sepal.Length」'是字符串的一部分。 – 2014-11-02 14:56:21

2

這裏的另一種選擇。您可以使用call對象來表示參數data,然後在參數列表中對其進行評估。

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

它看起來像這種替代解決方案也將與原始str載體工作。

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)) 
}) 
相關問題