how to loop 1 item per list in a nested loop
number <- 1:4
child <- list("kelvin","john","bri","thorne")
for(x in number) {
for(y in child) {
print(paste(x,y))
}
}
I want to print
1 kelvin
2 john
3 Bri
4 Thorne
The issue with your current code is that you are performing a double loop instead of a single loop. By using a double loop, you are performing an action for each combination of number
and child
- when in reality, you only want to do one thing for each corresponding pair of these vectors.
You could start by just iterating on the number of elements of the vectors:
for (i in seq_along(number)) {
print(paste(number[i], child[i]))
}
[1] "1 kelvin"
[1] "2 john"
[1] "3 bri"
[1] "4 thorne"
If you want to use the x in v
style, you could create a list of lists that contain both the number and name for each child.
people = list(
list(number = 1, name = "kelvin"),
list(number = 2, name = "john"),
list(number = 3, name = "bri"),
list(number = 4, name = "thorne")
)
for (person in people) {
print(paste(person$number, person$name))
}
[1] "1 kelvin"
[1] "2 john"
[1] "3 bri"
[1] "4 thorne"
Finally, here's a tidyverse way using purrr::pwalk()
.
library(tidyverse)
people = list(number = number, child = child)
pwalk(people, ~ print(paste(.x, .y)))
[1] "1 kelvin"
[1] "2 john"
[1] "3 bri"
[1] "4 thorne"
Above, pwalk()
applies the anonymous function to each corresponding pairs of the elements of our newly-created list people
, which is exactly what we want here.