Paste0 multiple lists of different lengths without loop
I am inserting a bunch of variables into the final url list
id <- 1:10
animal <- c("dog", "cat", "fish")
base <- "www.google.com/"
urls <- paste0(base, "id=", id, "search=", animal)
The result looks like this:
[1] "www.google.com/id=1search=dog" "www.google.com/id=2search=cat" "www.google.com/id=3search=fish"
[4] "www.google.com/id=4search=dog" "www.google.com/id=5search=cat" "www.google.com/id=6search=fish"
[7] "www.google.com/id=7search=dog" "www.google.com/id=8search=cat" "www.google.com/id=9search=fish"
[10] "www.google.com/id=10search=dog"
But I really want to ids
, and animals
repeated in the following order:
[1] "www.google.com/id=1search=dog" "www.google.com/id=2search=dog" "www.google.com/id=3search=dog"
[4] "www.google.com/id=4search=dog" "www.google.com/id=5search=dog" "www.google.com/id=6search=dog"
[7] "www.google.com/id=7search=dog" "www.google.com/id=8search=dog" "www.google.com/id=9search=dog"
[10] "www.google.com/id=10search=dog" "www.google.com/id=1search=cat" ...
+3
source to share
1 answer
You can change the code by including rep
in paste0
orsprintf
sprintf('%sid=%dsearch=%s', base, id, rep(animal,each=length(id)))
or
paste0(base, 'id=',id, 'search=', rep(animal,each=length(id)))
Or, as @MrFlick suggested, we can use expand.grid
to get all the combinations between "animals" and "id"
with(expand.grid(a=animal, i=id), paste0(base, "id=", i, "search=", a))
+4
source to share