从 R data.table 中的每一列中减去每一列 [英] Subtract every column from each other column in a R data.table

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

问题描述

假设我有一个 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 data.table 中的每一列中减去每一列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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