Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Repetitive sum of a number of columns without for loop in R

Tags:

r

I have an matrix of T*12 rows and 3 columns. For each column, I want to sum the first set of 12 rows, then the second set of 12 rows and so on until the last (T=20) set of 12 rows.

I managed to do it with a for loop (below) but I would like to do it without the loop.

T=20
for (i in 1:T){
j <- (i-1)*12+1
Ryear[i,] <- colSums(R[j:(j+11),])
}
like image 731
ArnoLB Avatar asked Mar 17 '23 17:03

ArnoLB


2 Answers

A dplyr approach based on sample data by @akrun:

library(dplyr)

as.data.frame(R) %>% 
  group_by(grp = rep(seq_len(20), each = 12)) %>% 
  summarise_each(funs(sum))   # add %>% select(-grp) to drop the "grp" column

#Source: local data frame [20 x 4]
#
#   grp  V1  V2  V3
#1    1 136 153 144
#2    2 105 118 155
#3    3  94 149 122
#4    4 110 134 133
#5    5 120 114 102
#6    6 118 122 133
#7    7 116  96 120
#8    8 130 113 113
#9    9 113 140  97
#10  10 135 152 114
#11  11 148 139 148
#12  12 100 153  92
#13  13 136  99 141
#14  14 100 132 124
#15  15 121 139 133
#16  16 124 115 140
#17  17 168 127 129
#18  18 108 110  89
#19  19 115 152 108
#20  20 105 143 134
like image 120
talat Avatar answered Mar 19 '23 07:03

talat


You could convert the matrix to 'array' and then do the 'sum'

R1 <- R
dim(R1) <- c(12, 20, 3)
res <- apply(aperm(R1, c(1,3,2)),2, colSums)
identical(res, Ryear) #Ryear based on the results from the OP's code
#[1] TRUE

data

 set.seed(24)
 R <- matrix(sample(1:20, 20*12*3, replace=TRUE), nrow=20*12, ncol=3)
 Ryear <- matrix(,nrow=20, ncol=3)
like image 41
akrun Avatar answered Mar 19 '23 07:03

akrun