How to calculate the average excluding zeroes in R?

Asked

Viewed 373 times

2

I averaged the following values:

MÉDIA = mean(c(12,20,15,0,7,0))

print(MÉDIA)

[1] "9"

But I need the average that doesn’t consider zeroes:

MÉDIA_Sem Zeros = mean(c(12,20,15,7))

print(MÉDIA_Sem Zeros)

[1] "13,5"

How can I calculate the mean with the condition excluding the variables of zero value?

2 answers

6


Just index the vector to exclude zeros.

x <- c(12,20,15,0,7,0)
mean(x[x != 0])
#[1] 13.5

If the vector has values NA, use the argument na.rm = TRUE or the function which.

y <- x
y[3] <- NA

mean(y[y != 0], na.rm = TRUE)
#[1] 13

mean(y[which(y != 0)])
#[1] 13
  • Thank you for the answer I will test.

1

Another solution is to use the function subset:

x <- c(12,20,15,0,7,0)

mean(subset(x, x != 0))
[1] 13.5

or

mean(subset(x, x > 0))
[1] 13.5

However, it is preferable to give preference to the operator [, as @Rui proposed. Nesta question there is a more detailed explanation about the preference of the use of [ instead of subset.

  • Thank you for the answer I will test.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.