$\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:

• You cannot load any external packages or use any other functions (e.g., sum, mean, or anything else.)

To win

• You must email me your code brantly.callaway@uga.edu

• I’ll run your function, and if it can compute the average of a vector of numbers, you 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