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.
13
votes
2 Answers
20
votes
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)