for (item in list_of_items) {
do_something(item)
}
For loops
For Loops
Loops are a fundamental structure for repetition in programming. for
loops perform the same action for each item in a list of things. The basic syntax is:
We can create a vector on the fly to loop a particular number of times:
for (i in 1:5){
print(i)
}
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
Or use a pre-existing vector or list.
= c(1.6, 3, 8)
volumes for (volume in volumes){
<- 2.65 * volume ^ 0.9
mass print(mass)
}
[1] 4.045329
[1] 7.12287
[1] 17.21975
We also might want to loop over indices so we can access multiple vectors.
<- c(2.65, 1.28, 3.29)
as <- c(0.9, 1.1, 1.2)
bs = c(1.6, 3, 8)
volumes <- vector(mode="numeric", length=length(volumes))
masses for (i in 1:length(volumes)){
<- as[i] * volumes[i] ^ bs[i]
mass <- mass
masses[i]
} masses
[1] 4.045329 4.285913 39.893660
We can use functions inside loops. For example, let’s take a function that returns an estimated mass if the volume > 5
and NA
if it’s not.
<- function(volume, a, b){
est_mass if (volume > 5) {
<- a * volume ^ b
mass else {
} <- NA
mass
}return(mass)
}
We can then call the function to populate a vector item by item.
<- vector(mode="numeric", length=length(volumes))
masses for (i in 1:length(volumes)){
<- est_mass(volumes[i], as[i], bs[i])
mass <- mass
masses[i]
} masses
[1] NA NA 39.89366
To note, this is the for loop equivalent of an mapply
statement.
<- mapply(est_mass, volumes, as, bs)
masses_apply masses_apply
[1] NA NA 39.89366
In R we often want to use apply
statements as opposed to explicitly writing loops.
The materials in this lesson have been adapted from work created by the (HBC)](http://bioinformatics.sph.harvard.edu/) and Data Carpentry (http://datacarpentry.org/), as well as materials created by Laurent Gatto, Charlotte Soneson, Jenny Drnevich, Robert Castelo, and Kevin Rue-Albert. These are open access materials distributed under the terms of the Creative Commons Attribution license (CC BY 4.0), which permits unrestricted use, distribution, and reproduction in any medium, provided the original author and source are credited.