Hi, You could try: set.seed(24) mat1<- matrix(sample(0:5,10*20,replace=TRUE),ncol=20) mat2<- mat1 mat2[2,1:19]<-0 sapply(split(mat2,row(mat2)),function(x) sum(x[x!=0][1:3],na.rm=TRUE)) # 1 2 3 4 5 6 7 8 9 10 # 5 2 12 8 5 14 6 10 10 8 mat3<- mat2 mat3[2,]<- 0 sapply(split(mat3,row(mat3)),function(x) sum(x[x!=0][1:3],na.rm=TRUE)) # 1 2 3 4 5 6 7 8 9 10 # 5 0 12 8 5 14 6 10 10 8 A.K.
----- Original Message ----- From: José Verhoeven <j...@memo2.nl> To: r-help@r-project.org Cc: Sent: Tuesday, May 21, 2013 5:16 AM Subject: [R] Sum first 3 non zero elements of row Hi there, I've got this matrix D with, say 10 rows and 20 columns. For each row I want to sum the first 3 non zero elements and put them in a vector z. So if the first row D[1,] is 0 3 5 0 8 9 3 2 4 0 then I want z z<-D[1,2]+D[1,3]+D[1,5] But if there are less than 3 non zero elements, those should be summed. If there are no non zero elements, the result must be zero. So if the first row D[1,] is 0 0 3 0 1 0 0 0 0 0 then I want z z<-D[1,3]+D[1,5] Hope someone can help me out! [[alternative HTML version deleted]] ______________________________________________ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code. ______________________________________________ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.