R Tutorial
Fundamentals of R
Variables
Input and Output
Decision Making
Control Flow
Functions
Strings
Vectors
Lists
Arrays
Matrices
Factors
DataFrames
Object Oriented Programming
Error Handling
File Handling
Packages in R
Data Interfaces
Data Visualization
Statistics
Machine Learning with R
In R, the for
loop is used for iteration. It allows you to execute a block of code multiple times, which can be particularly useful for data manipulation, simulations, and many other tasks. In this tutorial, we'll explore the syntax and usage of the for
loop in R.
for
Loop:The basic syntax of the for
loop in R is as follows:
for (value in sequence) { # Code to be executed for each value }
Here, sequence
is a vector of values and the loop will iterate over each value in this sequence.
for
Loop Example:Looping over a numeric sequence:
for (i in 1:5) { print(i) }
This will print numbers from 1 to 5.
You can loop over any vector, not just a sequence of numbers:
fruits <- c("apple", "banana", "cherry") for (fruit in fruits) { print(fruit) }
This will print each fruit in the fruits
vector.
for
Loops:You can nest for
loops inside each other:
for (i in 1:3) { for (j in 1:2) { print(paste(i, j)) } }
This will print combinations of i
and j
for the given ranges.
for
Loops for Data Manipulation:Suppose you have a matrix, and you want to compute the sum of each row:
mat <- matrix(1:9, nrow = 3) row_sums <- numeric(nrow(mat)) for (i in 1:nrow(mat)) { row_sums[i] <- sum(mat[i, ]) } print(row_sums)
When using for
loops, especially with larger datasets or vectors, it's a good practice to preallocate memory for the object that will store the results to make the loop run faster:
n <- 10000 results <- numeric(n) for (i in 1:n) { results[i] <- i^2 }
In this example, we preallocate a numeric vector of length n
before executing the loop.
for
Loops:While for
loops are useful, R provides functions that can often replace loops and are more efficient in terms of speed:
lapply()
, sapply()
, apply()
, etc. for applying functions over list or array-like structures.purrr::map()
and related functions (from the purrr
package) for more consistent and advanced mapping functionalities.The for
loop in R is a foundational control structure that allows for iterative execution of code. While there are often more efficient ways to accomplish many tasks in R without loops (thanks to R's vectorized nature), understanding and knowing how to use for
loops is essential, especially when the task at hand requires explicit iteration.
For loop in R:
# Simple for loop in R for (i in 1:5) { print(paste("Iteration", i)) }
Using for loop for iteration in R:
# Using for loop for iteration for (num in 1:3) { print(paste("Number:", num)) }
R for loop examples:
# More for loop examples for (letter in c("A", "B", "C")) { print(paste("Letter:", letter)) }
Nested for loops in R:
# Nested for loops in R for (i in 1:3) { for (j in 1:2) { print(paste("Iteration:", i, "-", j)) } }
Looping through lists in R:
# Looping through a list in R my_list <- list("apple", "banana", "cherry") for (fruit in my_list) { print(paste("Fruit:", fruit)) }
Iterating over data frames with for loop in R:
# Iterating over data frames with for loop my_df <- data.frame(Name = c("Alice", "Bob", "Charlie"), Age = c(25, 30, 22)) for (col_name in colnames(my_df)) { print(paste("Column:", col_name)) print(my_df[, col_name]) }
Break and next statements in R for loops:
break
and next
statements in R for loops. break
is used to exit the loop prematurely, while next
skips the rest of the current iteration.# Break and next statements in R for loops for (i in 1:10) { if (i == 5) { break # Exit the loop when i equals 5 } if (i %% 2 == 0) { next # Skip even numbers } print(i) }