For loop is irreplaceable feature of R programming language, and many other languages for that matter. It's design for iteration through a list of known number of elements.
for(i in c(1:10)){
message(i)
}
In this case, c(1: 10) is holding integers from 1 to 10. In first iteration, i is going to be 1, and in every next iteration i is going to take next value from the collection.
for(i in c(1, 2, 3)){
message(i)
}
In second case, c(1, 2, 3) holds three elements 1, 2 and 3. In first iterations i is going to hold value of 1 in second 2 and at the end 3. So, element from the collection per iteration.
a <- c(1,2,3,4,5)
for(i in c(1:length(a))){
message(a[i])
}
Now, we are taking different approach. We are not iterating through collection a itself but through the collection of integer numbers from 1 to the number of elements of collection a. For that reason, to function message, we have to provide collection a and i as index that we are iterating through.
a <- c(1:10)[c(TRUE, FALSE)]
for(i in a){
message(i)
}
Now statement [c(TRUE, FALSE)] is going to populate collection a with every odd number in between 1 and 10.
Video tutorial link below.
No comments:
Post a Comment