[R] Applying function to elements of matrices in a list
Peter Ehlers
ehlers at ucalgary.ca
Thu Nov 25 16:30:32 CET 2010
On 2010-11-25 07:06, statmobile wrote:
> On 11/25/2010 09:44 AM, Dimitris Rizopoulos wrote:
>> try this:
>>
>> Reduce("+", x) / length(x)
>
> Thanks Dimitris, that's very slick, I was unaware of this Reduce function.
>
> The issue, is that I actually wanted to do a trimmed mean, and if things
> prove possible even the median.
>
> Is there a way to apply a generic function in the manner I described?
>
You could use the abind function in the abind package to
convert your list to a 3d array and then use apply on that:
require(abind)
xa <- abind(x, along=3)
apply(xa, 1:2, mean, trim=0.3)
Peter Ehlers
> Thanks,
> Brian
>
>>
>>
>> Best,
>> Dimitris
>>
>>
>> On 11/25/2010 3:42 PM, statmobile wrote:
>>> Hello R-help,
>>>
>>> Please cc me on all responses, as I only receive summary emails from
>>> this list.
>>>
>>> I'm wondering if anybody has any tips on how to accomplish this
>>> efficiently. I have a list of matrices, and I'm trying to get the mean
>>> of the [i,j]'th element of each matrix in a list.
>>>
>>> So if I have a list of matrices, say
>>>
>>> x<- list(a=matrix(rnorm(4),nrow=2),b=matrix(rnorm(4),nrow=2))
>>>
>>> How would I get a 2x2 matrix, where the i,j'th element would be the mean
>>> across the the list of each of the i,j'th elements in the list? That is,
>>> where the [1,2] element would be the average of a[1,2] and b[1,2].
>>>
>>> Of course my list and matrices are much larger, and I was hoping there
>>> would be some trick with lapply that I may be missing here.
>>>
>>> Thanks,
>>> Brian
>>>
>>> ______________________________________________
>>> 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.
>>>
>>
>
> ______________________________________________
> 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