...

/

For Loops

For Loops

Get introduced to loops for repetitive tasks.

What’s a for loop?

Probably the simplest way to automate completing some task is to use a for loop, which is simply a command that specifies a task or tasks to be completed a set number of times. Essentially, a for loop runs like this:

for(i in *vector of number of times to do task*)
{
*task to be completed*
print(*return some output to the console*)
}

Example

For example, imagine we’re doing a study with 20 mice, and we want to make a numbered list of the mice in our study. We could easily use a for loop to quickly generate this list.

R
for(i in 1:20) {
temp<-paste("mouse", i)
print(temp)
}

The important things to note in the code above are as follows:

  • Line 1: We defined a variable called i ...