Search code examples
rdataframeframe

Is there a way to make addition of two contiguos columns in R?


I have a data frame where each observation is comprehended in two columns. In this way, columns 1 and 2 represents the individual 1, 3 and 4 the individual 2 and so on.

Basically what I want to do is to add two contigous columns so I have the individual real score.

In this example V1 and V2 represent individual I and V3 and V4 represent individual II. So for the result data frame I will have the half of columns, the same number of rows and each value will be the addition of each value between two contigous colums.

Data

  V1 V2 V3 V4
1  0  0  1  1
2  1  0  0  0
3  0  1  1  1
4  0  1  0  1

Desire Output

  I II
1 0  2
2 1  0
3 1  2
4 1  1

I tried something like this

a <- data.frame(V1= c(0,1,0,0),V2=c(0,0,1,1),V3=c(1,0,1,0),V4=c(1,0,1,1))
b <- data.frame(NA, nrow = nrow(a), ncol = ncol(data))
for (i in seq(2,ncol(a),by=2)){
  for (k in 1:nrow(a)){
    b[k,i] <- a[k,i] + a[k,i-1]
  }
}
b <- as.data.frame(b)
b <- b[,-c(seq(1,length(b),by=2))]

Is there a way to make it simplier?


Solution

  • We could use split.default to split the data and then do rowSums by looping over the list

    sapply(split.default(a, as.integer(gl(ncol(a), 2, ncol(a)))), rowSums)
         1 2
    [1,] 0 2
    [2,] 1 0
    [3,] 1 2
    [4,] 1 1