Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R Sum columns by index

Tags:

r

I need to find a way to sum columns by their index,I'm working on a bigread.csv file, I'll show here a sample of the problem; I'd like for example to sum from the 2nd to the 5th and from the 6th to the 7h the following matrix:

a 1  3  3  4  5  6 
b 2  1  4  3  4  1 
c 1  3  2  1  1  5 
d 2  2  4  3  1  3 

The result has to be like this:

a 11 11
b 10  5
c  7  6
d  8  4

The columns have all different names

like image 551
Jua' Avatar asked Sep 02 '25 02:09

Jua'


1 Answers

We can use rowSums on the subset of columns i.e 2:5 and 6:7 separately and then create a new data.frame with the output.

data.frame(df1[1], Sum1=rowSums(df1[2:5]), Sum2=rowSums(df1[6:7]))
#  id Sum1 Sum2
#1  a   11   11
#2  b   10    5
#3  c    7    6
#4  d   11    4
like image 191
akrun Avatar answered Oct 13 '25 22:10

akrun



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!