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
forloop can modify objects outside the loop. - FALSE: a
forloop checks its condition at the beginning of the loop. - FALSE: a
forloop can be nested inside another loop.
Which of the following is a vectorized operation in R?
- FALSE: This is a
forloop, not vectorized. - TRUE:
pasteis vectorized and can operate on each element ofx. - TRUE: This is a vectorized operation; R adds 1 to each element of
xsimultaneously. - TRUE:
lapplyapplies the function to each element ofx, which is a form of vectorization. - TRUE:
applyapplies thesumfunction across rows ofx, 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.