Calculate average, median excluding any given number

I have a matrix of size 5000 * 5000, with 90% values ​​as 0. Is there a ready-made solution for calculating the average value, the median for this matrix after the exception "0"?

One crude solution changes all 0 to NA and uses

median(x, na.rm=TRUE) 

Another solution is to manually scan the matrix and create another vector containing the values, and then calculate the average, median, etc.

Any other better alternative?

+6
source share
2 answers

If you need an average and average total matrix, try doing

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

If you want to see the median and middle row

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

If you want middle and middle colonial wise

 apply(x,2,function(x){mean(x[x>0])}) apply(x,2,function(x){median(x[x>0])}) 
+9
source

Also check out the general problem presented in:

Select matrix rows that satisfy the condition

he can introduce you to the tricks that R can use effectively.

0
source

Source: https://habr.com/ru/post/970884/


All Articles