我想通过使用原始列彼此相减来创建新列,我使用字符来表示所有新列的组合,然后我要使用它dplyr::mutate
来创建新列。中有问题foo <- eval(parse(text = paste(new.feature,collapse = ",")))
,谢谢您的回答。
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-Species,Sepal.Width-Petal.Length,Sepal.Width-Petal.Width, Sepal.Width-Species,Petal.Length-Petal.Width,Petal.Length-Species,Petal.Width-Species“
最后,我想用来mutate
创建新列,但是失败了。
您不能仅仅混合和匹配字符串和正确的语言表达。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")
以获取更多信息。(我也仅限于数字列,以避免出现有关因素减法的警告)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句