我将一堆变量粘贴到一个明确的网址列表中
id <- 1:10
animal <- c("dog", "cat", "fish")
base <- "www.google.com/"
urls <- paste0(base, "id=", id, "search=", animal)
输出如下:
[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"
但实际上我希望ids
和animals
按顺序重复:
[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" ...
答案 0 :(得分:6)
您可以在rep
或paste0
sprintf
来修改代码
sprintf('%sid=%dsearch=%s', base, id, rep(animal,each=length(id)))
或者
paste0(base, 'id=',id, 'search=', rep(animal,each=length(id)))
或者@MrFlick建议,我们可以使用expand.grid
获取动物&#39;之间的所有组合。并且&#39; id&#39;
with(expand.grid(a=animal, i=id), paste0(base, "id=", i, "search=", a))