I would like to sum/mean/min a list of lists and numbers to return the related lists. -1+2*c(1,1,0)+2+c(-1,10,-1) returns c(2,13,0) but sum(1,2*c(1,1,0),2,c(-1,10,-1)) returns 15 not a list. Using the suggestions of Gabor Grothendieck, Reduce('+',list(-1,2*c(1,1,0),2,c(-1,10,-1))) returns what we want, c(2,13,0). However, it seems that this way does not work to mean/min. So, how to mean/min a list of lists and numbers to return a list? Thanks, -james
On 12/07/2010 11:10 AM, guox at ucalgary.ca wrote:> I would like to sum/mean/min a list of lists and numbers to return the > related lists. > > -1+2*c(1,1,0)+2+c(-1,10,-1) returns c(2,13,0) but > sum(1,2*c(1,1,0),2,c(-1,10,-1)) returns 15 not a list. > Using the suggestions of Gabor Grothendieck, > Reduce('+',list(-1,2*c(1,1,0),2,c(-1,10,-1))) returns what we want, > c(2,13,0). > > However, it seems that this way does not work to mean/min. > So, how to mean/min a list of lists and numbers to return a list? Thanks,You need to be careful of terminology: c(1,1,0) is not a list, it's a vector. What you want is to apply functions componentwise to lists of vectors. One way to do that is to bind them into a matrix, and use apply. For example: M <- cbind(-1, c(1,1,0), c(-1,10,-1)) apply(M, 1, mean) Duncan Murdoch
On Jul 12, 2010, at 11:10 AM, guox at ucalgary.ca wrote:> I would like to sum/mean/min a list of lists and numbers to return the > related lists.You will advance in your understanding faster if you adopt the correct terminology:> > -1+2*c(1,1,0)+2+c(-1,10,-1) returns c(2,13,0) but... which is NOT a list, it is a vector.> sum(1,2*c(1,1,0),2,c(-1,10,-1)) returns 15 not a list. > Using the suggestions of Gabor Grothendieck, > Reduce('+',list(-1,2*c(1,1,0),2,c(-1,10,-1))) returns what we want, > c(2,13,0). > > However, it seems that this way does not work to mean/min.If you want a running cumulative mean of a vector, i.e, c( mean(vec[1]), mean(vec[1:2]), ,,, mean(vec) ): vec <- sample(1:20) sapply(1:length(vec), function(x) mean(vec[1:x])> So, how to mean/min a list of lists and numbers to return a list?Not a list and not working on "a list of lists". A vector. -- David Winsemius, MD West Hartford, CT
On 07/13/2010 01:10 AM, guox at ucalgary.ca wrote:> I would like to sum/mean/min a list of lists and numbers to return the > related lists. > > -1+2*c(1,1,0)+2+c(-1,10,-1) returns c(2,13,0) but > sum(1,2*c(1,1,0),2,c(-1,10,-1)) returns 15 not a list. > Using the suggestions of Gabor Grothendieck, > Reduce('+',list(-1,2*c(1,1,0),2,c(-1,10,-1))) returns what we want, > c(2,13,0). > > However, it seems that this way does not work to mean/min. > So, how to mean/min a list of lists and numbers to return a list? Thanks, >Hi James, If you really have a list, and not a vector as in your example, look at the "rapply" function in the base package. Jim