Skip to content

Instantly share code, notes, and snippets.

@DrNickRedfern
Last active September 8, 2022 09:40
Show Gist options
  • Save DrNickRedfern/6055e05140d30ed90da63011719deaa5 to your computer and use it in GitHub Desktop.
Save DrNickRedfern/6055e05140d30ed90da63011719deaa5 to your computer and use it in GitHub Desktop.
An illustration of a for loop in R
a <- 1:3
b <- 4:6
# Loop over every element in a and print the result of the i-th elememt of a plus 10
for (i in seq_along(a)){
print(i + 10)
}
[1] 11
[1] 12
[1] 13
# Nest for loops to multiply the i-th element of a with the j-th element of b
for (i in seq_along(a)){
for (j in seq_along((b))){
print(paste0(a[i], " times ", b[j], " equals ", a[i] * b[j]))
}
}
[1] "1 times 4 equals 4"
[1] "1 times 5 equals 5"
[1] "1 times 6 equals 6"
[1] "2 times 4 equals 8"
[1] "2 times 5 equals 10"
[1] "2 times 6 equals 12"
[1] "3 times 4 equals 12"
[1] "3 times 5 equals 15"
[1] "3 times 6 equals 18"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment