How to program a For Loop in R


Just apply! What does that even mean? Well, some R programmers will tell you to use the apply function (lapply or sapply) to loop. Why? because R supports vectors. So, a for loop is slower. I’m not sure this is always true nor does it matter for this how to exercise. However, the next tutorial will be to teach you how to write programs for the various apply functions, but right now I’ll assume you don’t care about speed and just want to write a for loop in R.

Lets start with a totally basic for loop in R:

for(i in 1:100){
  print("Hello world!")

What’s going to happen?
Whatever appears within the the curly brackets is repeated 100 times because the for loop command takes the i as the loop counter. R then creates a vector i with 1:100 in it.

Lets try another basic for loop example:

for (age in c(10,11,12,13,14,15)){
  print(paste("The age is", age))

The output is below:

[1] "The age is 10"
[1] "The age is 11"
[1] "The age is 12"
[1] "The age is 13"
[1] "The age is 14"
[1] "The age is 15"

Let’s do one more for loop in R just to make sure you understand what is happening with for loops:

x <- c(1,2,3,4,5,6)
count <- 0
for (i in x) {
    if(i %% 2 == 0)  count = count+1

The loop above iterates six times through the vector. For each iteration of i, R takes on the value of x.

Then R counts the number of even numbers in x. The answer is therefore "3" because there are three even numbers.

That is a pretty basic introduction to for loops in R. If you have any questions or need further examples just comment below.



Please enter your comment!
Please enter your name here