1

I have a data.frame in R that looks like

X1 X2 X3 X4
11  2  3  4
2   5  7  1
12  4  7  6
3   2  9  6

I want to sequentially merge every set of two rows into one by taking the sum of their values in each column.

X1  X2  X3  X4
13  7   10  5
15  6   16  12 

Here 13 = 11 + 2, 7 = 2 + 5, 10 = 3 + 7 and 5 = 4 + 1. I have no clue how can I do this in R. Can we use rbind or some similar function to achieve this in one or two lines of code?

  • 3
    `zoo::rollapply(df, 2, by = 2, sum)` – Sotos Mar 15 '17 at 08:14
  • Possible duplicate of [Can \`ddply\` (or similar) do a sliding window?](http://stackoverflow.com/questions/7225992/can-ddply-or-similar-do-a-sliding-window) – Sotos Mar 15 '17 at 08:15
  • or maybe [this for dupe](http://stackoverflow.com/questions/13771385/is-there-a-function-like-rollapply-for-data-frame) – Sotos Mar 15 '17 at 08:18

4 Answers4

2

We can split the dataframe into two groups of alternate rows and then use Reduce to add them element wise.

Reduce("+", split(df, c(TRUE, FALSE)))

#  X1 X2 X3 X4
#2 13  7 10  5
#4 15  6 16 12
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
1

maybe something like

df <- data.frame(a=1:10, b=10:19)

df[seq(1,nrow(df),2),] + df[seq(2,nrow(df),2),]
drmariod
  • 11,106
  • 16
  • 64
  • 110
1

Here is a solution with base R, which uses the recycling rule and indexing with a logical vector:

as.matrix(x)[c(TRUE, FALSE),] + as.matrix(x)[c(FALSE, TRUE),]

Testing the code:

x <- read.table(head=TRUE, text=
"X1 X2 X3 X4
11  2  3  4
2   5  7  1
12  4  7  6
3   2  9  6")
as.matrix(x)[c(TRUE, FALSE),] + as.matrix(x)[c(FALSE, TRUE),]
#     X1 X2 X3 X4
#[1,] 13  7 10  5
#[2,] 15  6 16 12
jogo
  • 12,469
  • 11
  • 37
  • 42
1

We can use rowsum

rowsum(df1, gl(nrow(df1), 2, nrow(df1)))
#  X1 X2 X3 X4
#1 13  7 10  5
#2 15  6 16 12
akrun
  • 874,273
  • 37
  • 540
  • 662