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 t开发者_如何学运维ogether.
Such that x3[2] = c(2,4,6,8,...) ?
Did you have this in mind?
x1[2]+x2[3]
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
精彩评论