[R] How to calculate the mean of all values in a list or dataframe

John Kane jrkrideau at yahoo.ca
Sat Jan 12 00:13:54 CET 2008


?lapply in the case of a list.

test=list(a=1:5, b=1:4)
lapply(test, mean)


--- "B. Bogart" <bbogart at sfu.ca> wrote:

> Hello all,
> 
> I've scoured the archives and google and I can't
> figure out how to
> amalgamate a set of vectors of differing lengths in
> such a way as I can
> calculate the mean easily.
> 
> The following dummy example contains vectors of
> length 1, but my data
> has vectors of various lengths.
> 
> R> test = list(); for(i in 1:5) {test = append(test,
> i)}
> 
> R> test
> [[1]]
> [1] 1
> 
> [[2]]
> [1] 2
> 
> [[3]]
> [1] 3
> 
> [[4]]
> [1] 4
> 
> [[5]]
> [1] 5
> 
> R> mean(test)
> [1] NA
> Warning message:
> argument is not numeric or logical: returning NA in:
> mean.default(test)
> 
> I need to be able to construct the structure in a
> loop, but it does not
> really matter what type that structure is. I just
> want to be able to
> boxplot() and mean() and other simple functions.
> Each index in the list
> (as in the case above) can be considered a run of a
> test, the values in
> that index the results of that run, which have
> different number of
> elements. I would like the mean of all the values in
> all the runs.
> 
> What is the best type for collecting a set of
> numeric vectors of
> differing lengths in a for loop for the most
> flexibility and ease of
> using functions on the whole data or parts of it?
> 
> Thanks for your time,
> B. Bogart
> 
> ______________________________________________
> 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.
>




More information about the R-help mailing list