0
0
R Programmingprogramming~10 mins

For loop in R Programming - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to print numbers from 1 to 5 using a for loop.

R Programming
for (i in [1]) {
  print(i)
}
Drag options to blanks, or click blank then click option'
Ac(1,5)
B1:5
Cseq(5,1)
Drange(1,5)
Attempts:
3 left
💡 Hint
Common Mistakes
Using c(1,5) which creates a vector with only two elements: 1 and 5.
Using seq(5,1) which counts backwards from 5 to 1.
Using range(1,5) which is not a valid function in R.
2fill in blank
medium

Complete the code to calculate the sum of numbers from 1 to 10 using a for loop.

R Programming
total <- 0
for (num in 1:10) {
  total <- total + [1]
}
print(total)
Drag options to blanks, or click blank then click option'
Anum
Btotal
C1:10
Dsum
Attempts:
3 left
💡 Hint
Common Mistakes
Adding the whole sequence 1:10 instead of the current number.
Adding the total to itself causing incorrect results.
Using sum which is a function, not a variable.
3fill in blank
hard

Fix the error in the for loop that prints each letter in the vector letters.

R Programming
letters <- c('a', 'b', 'c')
for ([1] in letters) {
  print(letter)
}
Drag options to blanks, or click blank then click option'
Ai
Bletters
Cletter
Dl
Attempts:
3 left
💡 Hint
Common Mistakes
Using a different variable name in the loop header and inside the loop.
Using the whole vector as the loop variable.
Using a variable name not defined in the loop.
4fill in blank
hard

Fill both blanks to create a named vector with squares of numbers greater than 3.

R Programming
nums <- 1:5
squares <- c()
for ([1] in nums) {
  if ([2] > 3) {
    squares[as.character(num)] <- num^2
  }
}
Drag options to blanks, or click blank then click option'
Anum
Bi
Attempts:
3 left
💡 Hint
Common Mistakes
Using the same variable name for both blanks causing confusion.
Using undefined variables in the condition.
Not matching variable names inside the loop.
5fill in blank
hard

Fill all three blanks to create a list of even numbers and their squares from 1 to 6.

R Programming
evens <- list()
for ([1] in 1:6) {
  if ([2] %% 2 == 0) {
    evens[[as.character([3])]] <- [2]^2
  }
}
Drag options to blanks, or click blank then click option'
Anum
Bi
Attempts:
3 left
💡 Hint
Common Mistakes
Mixing variable names causing undefined variable errors.
Using different variables in the condition and list key.
Not using the loop variable consistently.