0
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
1
  • 1
    You can just cat(paste(number, child), sep = "\n") Commented Jan 6, 2022 at 4:47

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.