Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to combine two rows in R?

Tags:

r

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.

like image 792
amwalker Avatar asked Jan 12 '16 23:01

amwalker


1 Answers

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
like image 85
thelatemail Avatar answered Sep 20 '22 19:09

thelatemail