12

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 ?

Mohit Verma
  • 2,019
  • 7
  • 25
  • 33

1 Answers1

20

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])})
vrajs5
  • 4,066
  • 1
  • 27
  • 44
  • 1
    if you use `! x %in% c(val1,val2)` you have a solution for excluding specific values instead of ranges. – Livius Jun 16 '14 at 06:43