While with a plot
Loops can be used for all kinds of fun examples! What if you wanted to visualize your debt decreasing over time? Like the last exercise, this one uses a loop to model paying it off, $500 at a time. However, at each iteration you will also append your remaining debt total to a plot, so that you can visualize the total decreasing as you go.
This exercise has already been done for you. Let's talk about what is happening here.
First, initialize some variables:
debt
= Your current debti
= Incremented each time debt is reduced. The next point on the x axis.x_axis
= A vector ofi
's. The x axis for the plots.y_axis
= A vector ofdebt
. The y axis for the plots.- Also, create the first plot. Just a single point of your current debt.
Then, create a while loop. As long as you still have debt:
debt
is reduced by 500.i
is incremented.x_axis
is extended by 1 more point.y_axis
is extended by the next debt point.- The next plot is created from the updated data.
After you run the code, you can use Previous Plot to go back and view all 11 of the created plots!
This exercise is part of the course
Intermediate R for Finance
Exercise instructions
- Just press Submit Answer after you finish exploring!
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
debt <- 5000 # initial debt
i <- 0 # x axis counter
x_axis <- i # x axis
y_axis <- debt # y axis
# Initial plot
plot(x_axis, y_axis, xlim = c(0,10), ylim = c(0,5000))
# Graph your debt
while (debt > 0) {
# Updating variables
debt <- debt - 500
i <- i + 1
x_axis <- c(x_axis, i)
y_axis <- c(y_axis, debt)
# Next plot
plot(x_axis, y_axis, xlim = c(0,10), ylim = c(0,5000))
}