r4ds-exercise-solutions icon indicating copy to clipboard operation
r4ds-exercise-solutions copied to clipboard

Exercise 19.2.4

Open zhaoxiliang opened this issue 3 years ago • 0 comments

The following function does not work for missing value, for example, x <- c(1:5, NA) variance(x)

NA variance(x, na.rm = TRUE) NA

variance <- function(x, na.rm = TRUE) { n <- length(x) m <- mean(x, na.rm = TRUE) sq_err <- (x - m)^2 sum(sq_err) / (n - 1) }

need to change as following: variance <- function(x, na.rm = TRUE) { n <- length(x) - sum(is.na(x)) m <- mean(x, na.rm = na.rm) sq_err <- (x - m)^2 sum(sq_err, na.rm = na.rm) / (n - 1) }

zhaoxiliang avatar Oct 30 '20 14:10 zhaoxiliang