8

I would like to combine/sum two rows based on rownames to make one row in R. The best route might be to create a new row and sum the two rows together.

Example df:

A  1  3  4  6  
B  3  2  7  9
C  6  8  1  2 
D  3  2  8  9

Where A,B,C,D are rownames, I want to combine/sum two rows (A & C) into one to get:

A+C  7  11  5  8  
B    3  2   7  9
D    3  2   8  9

Thank you.

1
  • 1
    You might want to review any number of intro to R texts, this is very basic data manipulation. Generally these type of operation are easier to perform on columns than rows so you might want to consider transposing your data. Jan 12, 2016 at 23:24

3 Answers 3

Reset to default

Trending sort

Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.

It falls back to sorting by highest score if no posts are trending.

8

aggregate to the rescue:

aggregate(df, list(Group=replace(rownames(df),rownames(df) %in% c("A","C"), "A&C")), sum)
#  Group V2 V3 V4 V5
#1   A&C  7 11  5  8
#2     B  3  2  7  9
#3     D  3  2  8  9
0
7

You can replace the A row using the standard addition arithmetic operator, and then remove the C row with a logical statement.

df["A", ] <- df["A", ] + df["C", ]
df[rownames(df) != "C", ]
#   V2 V3 V4 V5
# A  7 11  5  8
# B  3  2  7  9
# D  3  2  8  9

For more than two rows, you can use colSums() for the addition. This presumes the first value in nm is the one we are replacing/keeping.

nm <- c("A", "C")
df[nm[1], ] <- colSums(df[nm, ])
df[!rownames(df) %in% nm[-1], ]

I'll leave it up to you to change the row names. :)

Data:

df <- structure(list(V2 = c(1L, 3L, 6L, 3L), V3 = c(3L, 2L, 8L, 2L), 
    V4 = c(4L, 7L, 1L, 8L), V5 = c(6L, 9L, 2L, 9L)), .Names = c("V2", 
"V3", "V4", "V5"), class = "data.frame", row.names = c("A", "B", 
"C", "D"))
0

matrix multiply?

> A <- matrix(c(1,0,0,0,1,0,1,0,0,0,0,1), 3)
> A                                        
     [,1] [,2] [,3] [,4]
[1,]    1    0    1    0
[2,]    0    1    0    0
[3,]    0    0    0    1
> A %*% X
     V2 V3 V4 V5
[1,]  7 11  5  8
[2,]  3  2  7  9
[3,]  3  2  8  9

Or using the Matrix package for sparse matrices:

fac2sparse(factor(c(1,2,1,4))) %*% X

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.