Introduction to R: Exercises


6. Defining functions. You are given a vector of stock returns, which is stored as the variable returns. You want to write a function in R to standardize the returns.

Recall that a variable can be standardized by subtracting its mean and then dividing by its standard deviation. This can be done with the functions mean() and sd().

Functions in R have the following form: function_name <- function(arg_1, arg_2, ...){classFunction body}. The last expression to be evaluated in a function is its return value.


returns <- c(1.11, 0.98, -1.01, 1.93, -3.44, -3.74, 1.21, 4.05, 1.01, 1.51, -2.27) # Define a function to standardize a variable, X. standardize <- ___(X) { mean_X = mean(___) sd_X = ___(X) standardized_X = (___-mean_X)/___ } # Apply the function to the stock returns data. standardized_returns <- standardize(returns) # Plot histogram of returns. hist(standardized_returns) # Define a function to standardize a variable X. standardize <- function(X) { mean_X = mean(X) sd_X = sd(X) standardized_X = (X-mean_X)/sd_X } # Apply the function to the stock returns data. standardized_returns <- standardize(returns) # Plot histogram of returns. hist(standardized_returns) test_error() test_object("standardize", incorrect_msg="Did you apply the formula for standardization correctly?") test_object("standardized_returns", incorrect_msg="Did you define `standardized_X` correctly in `standardize`?") success_msg("Excellent work! Notice that the distribution is centered around 0.")
Did you apply the `mean()` and `sd()` functions correctly?

Previous Exercise Next Exercise