That's a good one, Using cumsum + rowsum would definitely be faster,
On Tue, May 21, 2013 at 6:40 AM, José Verhoeven <j...@memo2.nl> 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 <praguewaterme...@gmail.com> > >> 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) >> } #<----This was missing in the previous post >> >> >> set.seed(2) >> mat<-matrix(sample(0:4, 25, replace=T, prob=c(1/2,rep(1/8,4))), ncol=5) >> #add a right parenthesis. >> mat >> >> On Tue, May 21, 2013 at 3:47 AM, Xiao He <praguewaterme...@gmail.com>wrote: >> >>> 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,] 0 1 2 4 3 >>> #[2,] 3 0 0 1 0 >>> #[3,] 2 4 4 0 4 >>> #[4,] 0 0 0 0 0 >>> #[5,] 1 2 0 0 0 >>> >>> >>> apply(mat, 1, foo) #Apply the function to each row of the matrix >>> #[1] 7 4 10 0 3 >>> >>> >>> >>> On Tue, May 21, 2013 at 2:16 AM, José Verhoeven <j...@memo2.nl> wrote: >>> >>>> 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. >>>> >>> >>> >> > [[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.