[R] How to mean, min lists and numbers

David Winsemius dwinsemius at comcast.net
Mon Jul 12 17:44:27 CEST 2010


On Jul 12, 2010, at 11:19 AM, Duncan Murdoch wrote:

> 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)

As usual Duncan's understanding is better than mine. Just so you know,  
there are also utility functions row-oriented functions which are  
conisderably faster when they are the correct solution:

?rowSums
?rowMeans

 > rowMeans(cbind(-1, c(1,1,0), c(-1,10,-1)) )
[1] -0.3333333  3.3333333 -0.6666667
 >  apply(cbind(-1, c(1,1,0), c(-1,10,-1)), 1, mean)
[1] -0.3333333  3.3333333 -0.6666667

   ... and there is a parallel" version of a minimum functions, pmin  
that would have given you results for arguments that are just the  
vectors  of varying length you were working with:

 > pmin(2, c(2,2,0) ,-1 , c(-1,10,-1))
#[1] -1 -1 -1   #(Done with argument recycling.)


>
> Duncan Murdoch
>
> ______________________________________________
> R-help at 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.

David Winsemius, MD
West Hartford, CT



More information about the R-help mailing list