简体   繁体   中英

R Sum columns by index

I need to find a way to sum columns by their index,I'm working on a big read.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

We can use rowSums on the subset of columns ie 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

The package dplyr has a function exactly made for that purpose:

require(dplyr)
df1 = data.frame(a=c(1,2,3,4,3,3),b=c(1,2,3,2,1,2),c=c(1,2,3,21,2,3))
df2 = df1 %>% transmute(sum1 = a+b , sum2 = b+c) 
df2 = df1 %>% transmute(sum1 = .[[1]]+.[[2]], sum2 = .[[2]]+.[[3]])

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM