Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
294 views
in Technique[技术] by (71.8m points)

r - sum specific columns among rows

I need to sum every two columns for example

x1  x2  x3  x4
12  2   3   7
1   4   6   5

I need

X1     X2
14     10
5      11

I tried apply function and I tried this function mat is a matrix

mat1=matrix()

for(i in 1:nrow(mat)){
for(j in 1:ncol(mat)){
mat1[i,j]=mat[j,i]+mat[j,i+1]
}}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

A generalization of this problem (for a data.frame) might be something like:

sapply(split.default(mydf, 0:(length(mydf)-1) %/% 2), rowSums)
#       0  1
# [1,] 14 10
# [2,]  5 11

Replace the "2" in %/% 2 with the number of sets of columns you would like to "aggregate".


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...