To iterate over a two-dimensional vector in R, you can use nested loops.
In this example,
for
loops to iterate over each element of the two-dimensional vector.# Step 1: Iterate over a numeric two-dimensional vector
matrix <- list(c(1, 2, 3), c(4, 5, 6), c(7, 8, 9))
# Step 2: Nested loops to print each element
for (i in 1:length(matrix)) {
for (j in 1:length(matrix[[i]])) {
print(matrix[[i]][j])
}
}
1 2 3 4 5 6 7 8 9
In this example,
for
loops to iterate over each element of the two-dimensional vector.# Step 1: Iterate over a character two-dimensional vector
matrix <- list(c('a', 'b', 'c'), c('d', 'e', 'f'), c('g', 'h', 'i'))
# Step 2: Nested loops to print each element
for (i in 1:length(matrix)) {
for (j in 1:length(matrix[[i]])) {
print(matrix[[i]][j])
}
}
a b c d e f g h i
In this tutorial, we learned How to Iterate over a Two Dimensional Vector in R language with well detailed examples.