按组求和列对 [英] Sum pairs of columns by group

查看:105
本文介绍了按组求和列对的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望按组对成对的列进行求和.在下面的示例中,我希望对(v1v2),(v3v4)和(v5v6)对分别加r1r2r3.

I wish to sum pairs of columns by group. In the example below I wish to sum pairs (v1 and v2), (v3 and v4), and (v5 and v6), each by r1, r2 and r3.

我可以使用下面的sapply语句执行此操作,并且我得到正确的答案.但是,所需的代码很复杂.有人可以告诉我如何在软件包data.table中或使用rollapply和/或其他选项执行相同的操作吗?我尚未探索这些选项.

I can do this using the sapply statement below and I get the correct answer. However, the required code is complex. Could someone show me how to do the same operation perhaps in package data.table or with rollapply and/or other options? I have not yet explored those options.

对不起,如果重复的话.

Sorry if this is a duplicate.

my.data <- read.table(text= "
   r1  r2  r3    t1    t2    t3    v1   v2   v3   v4   v5   v6
    1   0   0    10    20    30     1    0    0    0    0    0
    1   0   0    10    20    30     1    1    0    0    0    0
    1   0   0    10    20    30     1    0    1    0    0    0
    1   0   0    10    20    30     1    0    1    1    0    0
    1   0   0    10    20    30     0    0    0    0    0    0

    0   1   0    10    20    30     0    1    1    1    1    1
    0   1   0    10    20    30     0    0    1    1    1    1
    0   1   0    10    20    30     0    0    0    1    1    1
    0   1   0    10    20    30     0    0    0    0    1    1
    0   1   0    10    20    30     0    0    0    0    0    1

    0   0   1    10    20    30     1    1    1    1    1    1
    0   0   1    10    20    30     1    0    1    1    1    1
    0   0   1    10    20    30     1    0    0    1    1    1
    0   0   1    10    20    30     1    0    0    0    1    1
    0   0   1    10    20    30     1    0    0    0    0    1
", header=TRUE, na.strings=NA)

my.data$my.group <- which(my.data[,1:3]==1, arr.ind=TRUE)[,2]
my.data

my.sums <- t(sapply(split(my.data[,7:(ncol(my.data)-1)], my.data$my.group), function(i) sapply(seq(2, ncol(i), 2), function(j) sum(i[,c((j-1),j)], na.rm=TRUE))))
my.sums

#   [,1] [,2] [,3]
# 1    5    3    0
# 2    1    5    9
# 3    6    5    9

推荐答案

这是一个非常通用的表达式,如果您希望它与特定的数据维/列名/等匹配,可以将其简化:

Here's a pretty general expression that you can probably simplify if you want it to match your specific data dimensions/column names/etc:

library(data.table)
dt = data.table(my.data)

dt[, lapply(1:(ncol(.SD)/2), function(x) sum(.SD[[2*x-1]], .SD[[2*x]])),
     by = eval(grep('^r', names(dt), value = TRUE)),
     .SDcols = grep('^v', names(dt), value = TRUE)]
#   r1 r2 r3 V1 V2 V3
#1:  1  0  0  5  3  0
#2:  0  1  0  1  5  9
#3:  0  0  1  6  5  9

这篇关于按组求和列对的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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