Introduction to R: Exercises


8. Extending a data frame. In some cases, we will want to extend a data frame by adding another column. We will often do this after transforming a variable. You can add a column to the dataframe df with the syntax df$column_name = variable.

You are given a data frame, bond_data that contains two columns: rate and risk_free. Compute the excess return and assign it to a column named excess_return.


bond_data = data.frame( risk_free = c(2.02, 2.02), rate <- c(11.05, 3.01) ) # Define a variable for the excess_return. excess_return <- bond_data$rate - ___ # Create new column for excess_return in bond_data. ___$excess_return <- ___ # Print data frame. ___(bond_data) # Define a variable for the excess_return. excess_return <- bond_data$rate - bond_data$risk_free # Create new column for excess_return in bond_data. bond_data$excess_return <- excess_return # Print data frame. print(bond_data) test_error() test_object("excess_return", incorrect_msg="Did you compute the excess return correctly?") test_function("print", incorrect_msg="Did you use the `print()` function?") success_msg("Well done!")
Remember that you can assign the variable X to the dataframe df using the syntax df$X=X.

Previous Exercise Next Exercise