2016-08-12 49 views
0

我想通过使用原始列相互减去创建新列,我用字符来表达所有新列的组合,然后我想用dplyr::mutate来创建新的列。 foo <- eval(parse(text = paste(new.feature,collapse = ",")))有问题,谢谢你的回答。有关使用字符串作为函数参数在R

col.names <- names(iris) 
sign.paste <- function(x){paste(x,collapse = "-")} 
new.feature <- apply(combn(col.names,2),2,sign.paste) 
paste(new.feature,collapse = ",") 
foo <- eval(parse(text = paste(new.feature,collapse = ","))) 
dplyr::mutate(iris,foo) 

当我使用paste(new.feature,collapse = ","),我会得到这样的

paste(new.feature,collapse = ",") 
[1]“Sepal.Length-Sepal.Width,Sepal.Length-Petal.Length,Sepal.Length字符-Petal.Width,Sepal.Length品种,Sepal.Width-Petal.Length,Sepal.Width-Petal.Width,Sepal.Width品种,Petal.Length-Petal.Width,Petal.Length品种,Petal.Width “物种”

终于,我想我们e mutate创建新列,但失败..

回答

1

您不能只是混合和匹配字符串和适当的语言表达式。如果可能,最好避免eval()。这里有一种方法来构建一个表达式来定义所有的减法,然后执行它。

col.names <- names(iris)[sapply(iris, is.numeric)] 
sign.paste <- function(x){substitute(x-y, list(x=as.name(x[1]), y=as.name(x[2])))} 
new.feature <- apply(combn(col.names,2),2,sign.paste) 

dplyr::mutate_(iris,.dots=new.feature) 

请注意,现在sign.paste返回语言表达式列表,而不是字符串。如果您评估了字符串,这基本上就是您设置的。然后我们确保使用mutate_这是mutate函数的标准评估版本。它允许我们将参数作为一个大列表而不是单独的参数传递。有关更多信息,请参阅vignette("nse")。 (我也仅限于数字栏以避免关于减法因素的警告)