Knowledge Quiz: Tutorial 1

Note
  • Click the check-mark button to check your answer.
  • Click the question-mark button to see an explanation of the solution.

What is the key difference between a for loop and a while loop?

  • TRUE
  • FALSE: Both loops have different behaviors and use cases.
  • FALSE: a for loop can modify objects outside the loop.
  • FALSE: a for loop checks its condition at the beginning of the loop.
  • FALSE: a for loop can be nested inside another loop.

Which of the following is a vectorized operation in R?

  • FALSE: This is a for loop, not vectorized.
  • TRUE: paste is vectorized and can operate on each element of x.
  • TRUE: This is a vectorized operation; R adds 1 to each element of x simultaneously.
  • TRUE: lapply applies the function to each element of x, which is a form of vectorization.
  • TRUE: apply applies the sum function across rows of x, which is vectorized.

What is missing in the following R code so that the loop returns these values?

{. .cell-code} for (i in 1:10) { __________________ a <- i^2 print(a) }

[1] 1
[1] 4
[1] 9
[1] 16
[1] 36
[1] 49
[1] 64
[1] 81
[1] 100

To skip the iteration when i is equal to 5, you need to add a conditional statement that checks for this condition and uses the next function to skip to the next iteration of the loop. The missing line is: if (i == 5) next.

Back to top