\[\newcommand{\E}{\mathbb{E}}\]

For today’s code challenge, all you need to do is to write a function, let’s call it average, that takes in a vector of numbers and computes the average of that vector of numbers.

Here’s the catch: You can only basic operations in R (e.g., +, -, *, /), for loops, if/else, and the length function.

Rules:

To win



Solution below…















average <- function(x) {
  n <- length(x)
  sumx <- 0
  for (i in 1:n) {
    sumx <- sumx + x[i]
  }
  sumx/n
}

average(mtcars$mpg)
## [1] 20.09062
mean(mtcars$mpg)
## [1] 20.09062