Introduction to R: Exercises


9. Loops. We will often want to access all of the elements of a data frame or vector in a sequence. We can do this using a for loop. The basic syntax is given below for printing elements 1 through N in vector X:for (i in 1:N){print(X[j])}.

You are given a vector of simple returns, simple_returns. Use a for loop and the log function to compute and print the log returns.


simple_returns <- c(0.05, 0.07, -0.03, 0.10, 0.21, -0.13, 0.12) # Use a loop to compute and print each log return. for (___ in 1:7) { print(___(___[i]+1)) } # Use a loop to compute and print each log return. for (i in 1:7) { print(log(simple_returns[i]+1)) } test_error() test_function("log", incorrect_msg="Did you use the `log` function to compute the natural logarithm?") success_msg("Well done! Do you know why we looped over the range 1:7? If not, try printing `simple_returns`.")
You can compute the natural logarithm of a number using the log() function.

Previous Exercise Next Exercise