Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I calculate the means of rows while excluding the zero values from rows in data frame

Tags:

r

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.

like image 663
Gongon Avatar asked Sep 25 '12 13:09

Gongon


People also ask

Should zero values be included in the calculation of mean?

Anyway, if you compile your protein matrix correctly, there should not be any missing values originating from technical causes in there at all, and in that case, you should definitely take 0-values into account when calculating a mean or median.

How do you calculate the mean of a row in R?

Calculate the mean of rows of a data frame in R To create a data frame in R, use the data. frame() function. To calculate the mean of rows of the data frame, use the rowMeans() function.

How do you count zeros in a row?

Select a blank cell and type this formula =COUNTIF(A1:H8,0) into it, and press Enter key, now all the zero cells excluding blank cells are counted out. Tip: In the above formula, A1:H8 is the data range you want to count the zeros from, you can change it as you need.

How do you calculate rows?

Once the first row is given, we can just add the total rows in the range and subtract 1 to get the last row number. For a very large number of ranges, we can use the INDEX function instead of the MIN function. The formula will be =ROW(INDEX(range,1,1))+ROWS(range)-1.


1 Answers

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.

like image 88
Ben Bolker Avatar answered Sep 27 '22 21:09

Ben Bolker