在R数据表中从每个其他列中减去每个列 [英] Subtract every column from each other column in a R data.table

查看:161
本文介绍了在R数据表中从每个其他列中减去每个列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个data.table

Let's say I have a data.table

set.seed(1) # to make the example reproducible
ex<-data.table(AAA=runif(100000),
               BBB=runif(100000),
               CCC=runif(100000),
               DDD=runif(100000),
               FLAG=c(rep(c("a","b","c","d","e"),200000)))

我要从 AAA 每隔一列减去 BBB 每个剩余的列(FLAG除外)等等,使输出看起来像...

I want to subtract from column AAA every other column, then from BBB every remaining column (except FLAG) and so on so that the output will look like...

ex[,list(AAA_BBB=AAA-BBB,
         AAA_CCC=AAA-CCC,
         AAA_DDD=AAA-DDD,
         BBB_CCC=BBB-CCC,
         BBB_DDD=BBB-DDD,
         CCC_DDD=CCC-DDD)]

有一个data.table语法可以做到这一点干净地不知道有多少列或它们的名字是什么?

Is there a data.table syntax that can do this cleanly without knowing how many columns there are or what their names are?

推荐答案

循环使用data.table中的组合:

Looping over the combinations within data.table:

comblist <- combn(names(ex)[-5],2,FUN=list)
res2 <- ex[,lapply(comblist,function(x) get(x[1])-get(x[2]))]

setnames(res2,names(res2),sapply(comblist,paste,collapse="_"))

这篇关于在R数据表中从每个其他列中减去每个列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆