Brandon Bertelsen
Brandon Bertelsen

Reputation: 44698

R: Summing dataframes

Suppose I have two similar data.frames

x1 <- data.frame(letters[1:26],1:26,1:26)
x2 <- data.frame(letters[1:26],1:26,1:26) 

How would I create a new data frame that adds the 2nd column of each data frame together and the 3rd column of each data frame together.

Such that x3[2] = c(2,4,6,8,...) ?

Upvotes: 0

Views: 172

Answers (2)

Gavin Simpson
Gavin Simpson

Reputation: 174948

Do you want:

> x3 <- data.frame(A = letters, S2 = x1[,2] + x2[,2], S3 = x1[,3] + x2[,3])
> head(x3)
  A S2 S3
1 a  2  2
2 b  4  4
3 c  6  6
4 d  8  8
5 e 10 10
6 f 12 12

If so, and you want a more general solution, perhaps consider mapply:

> head(mapply(`+`, x1[,2:3], x2[2:3]))
     X1.26 X1.26.1
[1,]     2       2
[2,]     4       4
[3,]     6       6
[4,]     8       8
[5,]    10      10
[6,]    12      12

Using this to construct a new data frame with the first column intact we have:

> x3 <- data.frame(letters, mapply(`+`, x1[,2:3], x2[2:3]))
> head(x3)
  letters X1.26 X1.26.1
1       a     2       2
2       b     4       4
3       c     6       6
4       d     8       8
5       e    10      10
6       f    12      12

Upvotes: 1

Roman Luštrik
Roman Luštrik

Reputation: 70653

Did you have this in mind?

x1[2]+x2[3]

Upvotes: 2

Related Questions