Re: [R] Sum first 3 non zero elements of row

2013-05-21 Thread José Verhoeven
Thank you, that really worked. Actually received an even shorter version: rowSums((t(apply(D > 0, 1, cumsum)) <= 3) * D) 2013/5/21 Xiao He > Oops, a couple of missing brackets in the previous reply: > > > foo<-function(x){ > temp=x[x>0] > if(length(temp)>=3) sum(temp[1:3]) > else sum(te

Re: [R] Sum first 3 non zero elements of row

2013-05-21 Thread Xiao He
That's a good one, Using cumsum + rowsum would definitely be faster, On Tue, May 21, 2013 at 6:40 AM, José Verhoeven wrote: > Thank you, that really worked. Actually received an even shorter version: > > > rowSums((t(apply(D > 0, 1, cumsum)) <= 3) * D) > > > > 2013/5/21 Xiao He > >> Oops, a co

Re: [R] Sum first 3 non zero elements of row

2013-05-21 Thread arun
(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 To: r-help@r-project.org Cc: Sent: Tuesday, May 21, 2013 5:16 AM Subject: [R] Sum first 3 non zero elements o

Re: [R] Sum first 3 non zero elements of row

2013-05-21 Thread Xiao He
Oops, a couple of missing brackets in the previous reply: foo<-function(x){ temp=x[x>0] if(length(temp)>=3) sum(temp[1:3]) else sum(temp) } #

Re: [R] Sum first 3 non zero elements of row

2013-05-21 Thread Xiao He
Does this work? Probably not the fastest, but I think it does the job. foo<-function(x){ temp=x[x>0] if(length(temp)>=3) sum(temp[1:3]) else sum(temp) set.seed(2) mat<-matrix(sample(0:4, 25, replace=T, prob=c(1/2,rep(1/8,4)), ncol=5) mat # [,1] [,2] [,3] [,4] [,5] #[1,]012

[R] Sum first 3 non zero elements of row

2013-05-21 Thread José Verhoeven
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 sho