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?
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
maybe something like
df <- data.frame(a=1:10, b=10:19)
df[seq(1,nrow(df),2),] + df[seq(2,nrow(df),2),]
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
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.