“for” loop
provides a compact way to iterate over a range of values.
Syntax
for(variable
in sequence){
Do some thing
}
ForEx.R
for(i in 1:10){ print (i) }
$ Rscript ForEx.R [1] 1 [1] 2 [1] 3 [1] 4 [1] 5 [1] 6 [1] 7 [1] 8 [1] 9 [1] 10
Traversing vector
You can
iterate through a vector in many ways. Following example shows different ways
to iterate through a vector.
TraverseVector.R
vector1 <- c(5, 6, 7, 8) print("Way1 to traverse vector") for(i in 1:4){ print (vector1[i]) } print("Way2 to traverse vector") for(i in seq_along(vector1)){ print(vector1[i]) } print("Way3 to traverse vector") for(i in vector1){ print(i) }
$ Rscript TraverseVector.R [1] "Way1 to traverse vector" [1] 5 [1] 6 [1] 7 [1] 8 [1] "Way2 to traverse vector" [1] 5 [1] 6 [1] 7 [1] 8 [1] "Way3 to traverse vector" [1] 5 [1] 6 [1] 7 [1] 8
Traverse a matrix using for loop
> matrix1 <- matrix(1:9, nrow=3, ncol=3) > matrix1 [,1] [,2] [,3] [1,] 1 4 7 [2,] 2 5 8 [3,] 3 6 9
PrintMatrix.R
matrix1 <- matrix(1:9, nrow=3, ncol=3) print("printing matrix using for loop") for(i in seq_len(nrow(matrix1))){ for(j in seq_len(ncol(matrix1))){ print (matrix1[i,j]) } }
$ Rscript PrintMatrix.R [1] "printing matrix using for loop" [1] 1 [1] 4 [1] 7 [1] 2 [1] 5 [1] 8 [1] 3 [1] 6 [1] 9
No comments:
Post a Comment