Skip to main content

6.9) Loops And Programming


In that example, note how we first created the object in which the output values were to be stored, using a simple command to establish its class (in this case list, so we can store composite data to each element – and remember that double square brackets are used to index list elements).

Don’t write a loop to go through simple vectors element by element; operations on vectors work this way by default. Rather, it’s more often necessary to use loops for going through lists or arrays vector by vector – or for longer repetitive procedures that you might specify in a function. But first check in case the function you’re applying, or a variant of it, can handle the whole object anyway. So S.means <- colMeans(swiss) actually gives the same result as:

S.means <- c()
for (i in 1:length(swiss))
   S.means[i] <- mean(swiss[[i]])

Loops can be an important element of programming, and R also has the standard programming functions while() and break(), and others. You can also make if()...else commands. But that's all beyond the scope of this course...

If you need more materials to take you further, go to "Additional Resources" in the menu on the left. Then to finish, visit the "Conclusion".