Get Started

Loop over a matrix

In your workspace, there's a matrix ttt, that represents the status of a tic-tac-toe game. It contains the values "X", "O" and "NA". Print out ttt to get a closer look. On row 1 and column 1, there's "O", while on row 3 and column 2 there's "NA".

To solve this exercise, you'll need a for loop inside a for loop, often called a nested loop. Doing this in R is a breeze! Simply use the following recipe:

for (var1 in seq1) {
  for (var2 in seq2) {
    expr
  }
}

This is a part of the course

“Intermediate R”

View Course

Exercise instructions

Finish the nested for loops to go over the elements in ttt:

  • The outer loop should loop over the rows, with loop index i (use 1:nrow(ttt)).
  • The inner loop should loop over the columns, with loop index j (use 1:ncol(ttt)).
  • Inside the inner loop, make use of print() and paste() to print out information in the following format: "On row i and column j the board contains x", where x is the value on that position.

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

# The tic-tac-toe matrix ttt has already been defined for you

# define the double for loop
for (___ in ___) {
  for (___ in ___) {
    print(___)
  }
}

This exercise is part of the course

Intermediate R

BeginnerSkill Level
4.5+
131 reviews

Continue your journey to becoming an R ninja by learning about conditional statements, loops, and vector functions.

Loops can come in handy on numerous occasions. While loops are like repeated if statements, the for loop is designed to iterate over all elements in a sequence. Learn about them in this chapter.

Exercise 1: While loopExercise 2: Write a while loopExercise 3: Throw in more conditionalsExercise 4: Stop the while loop: breakExercise 5: Build a while loop from scratchExercise 6: For loopExercise 7: Loop over a vectorExercise 8: Loop over a listExercise 9: Loop over a matrix
Exercise 10: Mix it up with control flowExercise 11: Next, you break itExercise 12: Build a for loop from scratch

What is DataCamp?

Learn the data skills you need online at your own pace—from non-coding essentials to data science and machine learning.

Start Learning for Free