Build a for loop from scratch
This exercise will not introduce any new concepts on for loops.
We already went ahead and defined a variable rquote. This variable has been split up into a vector that contains separate letters and has been stored in a vector chars with the strsplit() function.
Can you write code that counts the number of r's that come before the first u in rquote?
This exercise is part of the course
Intermediate R
Exercise instructions
- Initialize the variable
rcount, as 0. - Finish the
forloop: - if
charequals"r", increase the value ofrcountby 1. - if
charequals"u", leave theforloop entirely with abreak. - Finally, print out the variable
rcountto the console to see if your code is correct.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# Pre-defined variables
rquote <- "r's internals are irrefutably intriguing"
chars <- strsplit(rquote, split = "")[[1]]
# Initialize rcount
rcount <-
# Finish the for loop
for (char in chars) {
}
# Print out rcount