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.
Loading...
Related Quiz
- In R, a variable that contains a sequence of data is called a ________.
- In R, the ______ function can be used to calculate a weighted mean.
- What function is commonly used to calculate the mean in R?
- In R, the ______ function can be used to create a scatter plot with a regression line.
- Imagine you're working with a large data set in R and need to perform an operation on a vector that's not memory-efficient. How would you handle this situation?