3

I need to sum every two columns for example

x1  x2  x3  x4
12  2   3   7
1   4   6   5

I need

X1     X2
14     10
5      11

I tried apply function and I tried this function mat is a matrix

mat1=matrix()

for(i in 1:nrow(mat)){
for(j in 1:ncol(mat)){
mat1[i,j]=mat[j,i]+mat[j,i+1]
}}
user3478697
  • 243
  • 1
  • 3
  • 11
  • A5C1D2H2I1M1N2O1R2T1's answer uses `split.default`. Relevant: [What is the algorithm behind R core's `split` function?](https://stackoverflow.com/q/52158589/4891738) – Zheyuan Li Sep 04 '18 at 13:24

3 Answers3

8

A generalization of this problem (for a data.frame) might be something like:

sapply(split.default(mydf, 0:(length(mydf)-1) %/% 2), rowSums)
#       0  1
# [1,] 14 10
# [2,]  5 11

Replace the "2" in %/% 2 with the number of sets of columns you would like to "aggregate".

A5C1D2H2I1M1N2O1R2T1
  • 190,393
  • 28
  • 405
  • 485
2

For example:

 mat[,c(TRUE,FALSE)]+mat[,c(FALSE,TRUE)]

  x1 x3
1 14 10
2  5 11
agstudy
  • 119,832
  • 17
  • 199
  • 261
1
id <- 1:ncol(mat)
mat[ , id[id%%2!=0] ] + mat[ , id[id%%2==0] ]
     x1 x3
[1,] 14 10
[2,]  5 11
Simon O'Hanlon
  • 58,647
  • 14
  • 142
  • 184