13
votes

I am trying to calculate the mean of each row in my data frame. There are zeros in each row and I want to exclude these from calculation. I do not want to remove the entire row but only the zeros and calculate the mean of remaing values in each row. If row has all zero values than result should be Zero.

2

2 Answers

20
votes

How about

nzmean <- function(x) {
    if (all(x==0)) 0 else mean(x[x!=0])
}
apply(mydata,1,nzmean)

?

It occurs to me that it might be marginally faster to do

nzmean <- function(x) {
    zvals <- x==0
    if (all(zvals)) 0 else mean(x[!zvals])
}

i.e. try to avoid doing the comparison of x with zero twice.

15
votes

Or what you could do is assign NA to zero, which is effectively what you want to do. Some sample data:

spam = matrix(runif(100), 10, 10)
spam[1,2] = 0
spam[4,3] = 0
spam[10,] = 0
spam[spam == 0] <- NA

and use rowMeans, the ifelse is to check for rows that are entirely NA. The na.rm argument is important here:

mean_values = rowMeans(spam, na.rm = TRUE)
mean_values = ifelse(is.na(mean_values), 0, mean_values)