[R] functions within a list

David Winsemius
2009-03-20T04:18:46Z

On Mar 19, 2009, at 9:01 PM, Altaweel, Mark R. wrote:

> Hi,
>
> I am trying to perform various functions on a list with a number of
> elements. For example. I would like to take the mean of different
> variable values in the entire list. As an example,
> say I have a list with 1000 elements and variables called Id and
> Tick. What I would like to do is take the mean of a variable called
> X for each Tick in the data element. So, there can be say 1 to 600
> tick values per element in a list, that would mean I would like to
> find the 600 mean values for each of the ticks values in the 1000
> elements.
>
>
> I tried a simple attempt below, but I am sure it is way off as it
> didn't produce what I expected:
>
> //res=res[[1..1000]]
> weightX<-sapply(res, function(.df) {mean(.df$X[.df$Id>0 & .df
> $Tick<601])})
>
> Basically, I was trying to get the mean for all tick values less
> than 600 that have an Id variable greater than 0. So, since there
> are 600 ticks I would like to return a result with 600 mean values,
> for each of the 600 ticks, that factors all the 1000 occurrences of
> each tick, starting from 1.
>
> I hope this is clear. Thanks in advance.

It's not particularly clear, but the first part at least sounds as
though you should be looking at tapply rather than sapply. tapply
works with irregular tables defined by a factor. It might be clearer
if you produced the results of str() on your "list". I find myself
wondering if it is a dataframe or not.

tapply(df$X, df$Tick, mean)    # might be what you are seeking.

If not, then try to build a simple example as the posting guide and
this little message suggest:
>
> 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
Heritage Laboratories
West Hartford, CT