Skip to content
Back to formatted view

Raw Message

Message-ID: <866A1A3A-A90E-4C69-9C18-48CA612CEC15@xs4all.nl>
Date: 2012-08-18T06:13:02Z
From: Berend Hasselman
Subject: Row means of matrix.
In-Reply-To: <CAAuJZX+y_XFdmRQ4V7ZVigw8NP=K8vNQN6zMxTf8eMLpispmpw@mail.gmail.com>

On 18-08-2012, at 05:28, Yingwei Lee wrote:

> Hi all,
>          I'm just having trouble getting row means of a matrix which
> contain zero.
> For example.
> 
> m=matrix(c(1:4, c(0, 0, 0, 0), c(1, 0, 1, 1)), nc=4, byrow=TRUE)
> 
> I want to be able to calculate means for non-zero elements for each row.
> 
> ## what i have is this
> apply((m[apply(m != 0, MARGIN=1, any),]), 1, mean)
> ## which returns
> [1]  2.50  0.75
> 
> ### what i want to get returned is this
> [1] 2.50  *1
> 
> *meaning that the last row calculated the mean ignoring the zero. Anyone
> got any ideas?

Define function to compute mean of non zero elements

 f <- function(x) {k <- which(x!=0); mean(x[k])}

then use apply

apply(A,1,f)
[1] 2.5 NaN 1.0

and to remove the NaN you could do

z <- apply(A,1,f)
z[!is.na(z)]

or

z[is.finite(z)]

Berend