如何在一个R命令中评估多个变异?

时间:2016-06-20 18:48:42

标签: r dplyr

我在data.table中有60列,名为x.b.0x.a.0,0为0到59.我想添加60列,每列都是.b之间的对应差异和.a条目。因此,举例来说,我可以得到一个这样的所需列:

require(magittr)
require(dplyr)
x %>% mutate(x.diff.16 = x.a.16 - x.b.16) 

我尝试通过这样做立即让所有列适用于所有列:

formulas = sapply(0:59, function(i) { paste0('x.a.',i,' = x.a.',i,' - x.b.',i,')')}) 
foo = paste(formulas, collapse=',')
x %>% mutate(eval(parse(text=foo)))

但是这出乎意料地抱怨了,'。有没有更好的方法来做到这一点或解决方法?

以下是缩减表的示例:

require(data.table) 
set.seed(17)
x = data.table(x.a.0 = rnorm(10), x.b.0=rnorm(10), x.a.1=rnorm(10), x.b.1=rnorm(10), x.a.2=rnorm(10), x.b.2=rnorm(10))

这就是我最终做的事情:

x.mat = x %>% select(starts_with('x.')) %>% as.matrix()
k = ncol(x.mat / 2)
diff.mat = sapply(1:k, function(i) {v=c(rep(0,i-1),rep(0,k-i)); matrix(data=c(-v,v),ncol=k,byrow=TRUE)})
x.diff = x.mat %*% diff.mat
colnames(x.diff) = sapply(0:61, function(i) { paste0('x.n.',i)})
x = cbind(x, x.diff)

0 个答案:

没有答案