Reputation: 139
Is it possible to ignore negative values when calculating mean, min, max and standard deviation from an R integer array? I have a 22*22 array with many negative values of -128. I want to only consider the positive values and the count of positive values when calculating the above statistics.
Upvotes: 0
Views: 7355
Reputation: 206606
You can filter the values
#sample data
x<-c(4,1,10,-128,54,14,16,-128)
#filter helper function
isPositive <- function(x) x>=0
#calculate value(s)
mean(x)
#[1] -19.625
mean(Filter(isPositive, x))
# [1] 16.5
But if you have multiple -128 it sounds like that value might actually represent missing data. It may be easier to set those as NA
x[x==-128] <- NA
then you could just do
mean(x, na.rm=T)
# [1] 16.5
Upvotes: 2