How to Write a for-Loop with Larger Increments in R (Example Code)

In this R programming tutorial you’ll learn how to write for-loops with increments by 2.

Example Data

data(iris)                                          # Load iris data
my_iris <- iris[ , 1:4]                             # Modify iris
head(my_iris)                                       # Head of iris
#   Sepal.Length Sepal.Width Petal.Length Petal.Width
# 1          5.1         3.5          1.4         0.2
# 2          4.9         3.0          1.4         0.2
# 3          4.7         3.2          1.3         0.2
# 4          4.6         3.1          1.5         0.2
# 5          5.0         3.6          1.4         0.2
# 6          5.4         3.9          1.7         0.4

Example: Loop Over Every Second Row of Data (Larger Increments)

for(i in seq(from = 1, to = nrow(iris), by = 2)) {  # Start for-loop
  my_iris[i, ] <- my_iris[i, ] + 100                # Modify row of iris
}
head(my_iris)                                       # Head of updated iris
#   Sepal.Length Sepal.Width Petal.Length Petal.Width
# 1        105.1       103.5        101.4       100.2
# 2          4.9         3.0          1.4         0.2
# 3        104.7       103.2        101.3       100.2
# 4          4.6         3.1          1.5         0.2
# 5        105.0       103.6        101.4       100.2
# 6          5.4         3.9          1.7         0.4

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