Get startedGet started for free

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

View Course

Exercise instructions

  • Initialize the variable rcount, as 0.
  • Finish the for loop:
  • if char equals "r", increase the value of rcount by 1.
  • if char equals "u", leave the for loop entirely with a break.
  • Finally, print out the variable rcount to 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
Edit and Run Code