[R] how to calculate means of matrix elements

dxc13 dxc13 at health.state.ny.us
Tue May 19 14:49:34 CEST 2009


Easy enough.  What if some of the matrix elements contained missing values? 
Then how could you still calculate the means?  Example code below:
mat1 <- matrix(c(1,2,3,4,5,NA,7,8,9),3,3)
mat2 <- matrix(c(NA,6,1,9,0,5,8,2,7),3,3)
mat3 <- matrix(c(5,9,1,8,NA,3,7,2,4),3,3)


Gabor Grothendieck wrote:
> 
> Try this:
> 
> (mat1 + mat2 + mat3) / 3
> 
> On Mon, May 18, 2009 at 8:40 PM, dxc13 <dxc13 at health.state.ny.us> wrote:
>>
>> useR's,
>> I have several matrices of size 4x4 that I want to calculate means of
>> their
>> respective positions with.  For example, consider I have 3 matrices given
>> by
>> the code:
>> mat1 <- matrix(sample(1:20,16,replace=T),4,4)
>> mat2 <- matrix(sample(-5:15,16,replace=T),4,4)
>> mat3 <- matrix(sample(5:25,16,replace=T),4,4)
>>
>> The result I want is one matrix of size 4x4 in which position [1,1] is
>> the
>> mean of position [1,1] of the given three matrices.  The same goes for
>> all
>> other positions of the matrix.  If these three matrices are given in
>> separate text files, how can I write code that will get this result I
>> need?
>>
>> Thanks in advance,
>> dxc13
>> --
>> View this message in context:
>> http://www.nabble.com/how-to-calculate-means-of-matrix-elements-tp23607694p23607694.html
>> Sent from the R help mailing list archive at Nabble.com.
>>
>> ______________________________________________
>> 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.
> 
> 

-- 
View this message in context: http://www.nabble.com/how-to-calculate-means-of-matrix-elements-tp23607694p23615755.html
Sent from the R help mailing list archive at Nabble.com.




More information about the R-help mailing list