R for-Loop & while-Loop Over Variables & Rows of Data Frame (2 Examples)

This tutorial shows how to loop over the variables and rows of a data matrix in the R programming language.

Example Data

data(iris)                                    # Load iris data
head(iris)
#   Sepal.Length Sepal.Width Petal.Length Petal.Width Species
# 1          5.1         3.5          1.4         0.2  setosa
# 2          4.9         3.0          1.4         0.2  setosa
# 3          4.7         3.2          1.3         0.2  setosa
# 4          4.6         3.1          1.5         0.2  setosa
# 5          5.0         3.6          1.4         0.2  setosa
# 6          5.4         3.9          1.7         0.4  setosa

Example 1: Looping Over Columns of Data Frame Using for-Loop

for(index in 1:ncol(iris)) {                  # Head of for-loop
  
  if(is.numeric(iris[ , index])) {            # if-condition
    
    iris[ , index] <- iris[ , index] + 100    # Body of for-loop
  }
}
head(iris)                                    # Return head of modified iris data
#   Sepal.Length Sepal.Width Petal.Length Petal.Width Species
# 1        105.1       103.5        101.4       100.2  setosa
# 2        104.9       103.0        101.4       100.2  setosa
# 3        104.7       103.2        101.3       100.2  setosa
# 4        104.6       103.1        101.5       100.2  setosa
# 5        105.0       103.6        101.4       100.2  setosa
# 6        105.4       103.9        101.7       100.4  setosa

Example 2: Looping Over Columns of Data Frame Using while-Loop

index <- 1                                    # Specify index
while(is.numeric(iris[ , index])) {           # Head of for-loop
  
  iris[ , index] <- iris[ , index] * 5        # Body of for-loop
  index <- index + 1                          # Increase index
}
head(iris)                                    # Return head of modified iris data
#   Sepal.Length Sepal.Width Petal.Length Petal.Width Species
# 1        525.5       517.5        507.0         501  setosa
# 2        524.5       515.0        507.0         501  setosa
# 3        523.5       516.0        506.5         501  setosa
# 4        523.0       515.5        507.5         501  setosa
# 5        525.0       518.0        507.0         501  setosa
# 6        527.0       519.5        508.5         502  setosa

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed

Menu
Top