Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate mean, median by excluding any given number

Tags:

r

I have a matrix of size 5000*5000, with 90% values as 0. Is there a ready-made solution available to calculate the mean, median for this matrix after excluding '0' ?

One crude solution is change all 0 to NA and use

 median(x, na.rm=TRUE)

Another solution is to manually scan the matrix and create another vector containing values and then figure out mean, median etc.

Any other better alternative ?

like image 501
Mohit Verma Avatar asked Jun 16 '14 06:06

Mohit Verma


1 Answers

If you want median and mean of overall matrix then try following

median(x[x>0])
mean(x[x>0])

If you want median and mean row wise

apply(x,1,function(x){mean(x[x>0])})
apply(x,1,function(x){median(x[x>0])})

If you want median and mean coloumn wise

apply(x,2,function(x){mean(x[x>0])})
apply(x,2,function(x){median(x[x>0])})
like image 51
vrajs5 Avatar answered Oct 12 '22 20:10

vrajs5