melik
melik

Reputation: 1332

How to compute mean of non zero elements of each row in a dataframe in r

I would like to compute mean for non-zero elements for each row. Below is a an example data set

data=data.frame(x1=c(8,0,9),x2=c(0,0,10),x3=c(16,10,2))
data
x1  x2  x3
8   0   16
0   0   10
9   10  2

The desired outcome will be

mean
12
10
 7

Thank you.

Not:getting column means for non zero data

I did try but it is not working since when I convert to NA value the mean will be NA.

Upvotes: 1

Views: 1104

Answers (2)

JCR
JCR

Reputation: 71

here's a simple solution:

apply(data,1,function(x) mean(x[x!=0]))

Upvotes: 2

akrun
akrun

Reputation: 887691

We replace the '0' with NA and make use of the na.rm parameter from rowMeans

rowMeans(replace(data, data == 0, NA), na.rm = TRUE)
#[1] 12 10  7

Upvotes: 4

Related Questions