R- For循环用于非顺序列表

时间:2016-10-22 02:40:10

标签: r string for-loop nonsequential

这可能是一个简单的问题,但我正在努力寻找一种方法来做相当于“for(i in 1:10){do something}”但使用一系列字符串。例如:

给出一个字符串列表a =(“Joe”,“John”,“George”)我想要做以下事情:

for (a in "Joe":"George"){
  url <- paste0(http://www.website.com/", a)
  readHTMLTable(url)
}

并让函数遍历名称列表并使用每个名称命中url。 感谢。

2 个答案:

答案 0 :(得分:0)

你和for (i in 1:length(a)) { etc }一起去,但是出于速度原因,通常情况下首先应用函数是正常的。

答案 1 :(得分:0)

使用&#34;&#34;在paste0函数中

a = c("Joe", "John", "George")

for (i in 1:length(a)){
  url <- paste0("http://www.website.com/", a)
      readHTMLTable(url)
}

lapply(a, function(x){paste0("http://www.website.com/", x)})
[[1]]
[1] "http://www.website.com/Joe"

[[2]]
[1] "http://www.website.com/John"

[[3]]
[1] "http://www.website.com/George"

sapply(a, function(x){paste0("http://www.website.com/", x)})

Joe                            John                          George 
"http://www.website.com/Joe"   "http://www.website.com/John" "http://www.website.com/George"