Suppose you're asked to write a function in R that calculates the average of a vector of numbers. How would you do it?

  • average <- function(x) { sum(x) / length(x) }
  • average <- function(x) { mean(x) }
  • average <- function(x) { total <- 0; for (num in x) { total <- total + num }; total / length(x) }
  • All of the above
To write a function in R that calculates the average of a vector of numbers, you can use the following code: average <- function(x) { sum(x) / length(x) }. The function takes a vector x as input, calculates the sum of the elements in x, divides it by the length of x, and returns the average value.
Add your answer
Loading...

Leave a comment

Your email address will not be published. Required fields are marked *