0

This is probably a simple question, but I'm struggling finding a way to do the equivalent of "for (i in 1:10){ do something}" but with a list of strings. For example:

given a list of strings a = ("Joe", "John", "George") I'd want to do the following:

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

and have the function traverse through the list of names and hit the url with each name. Thanks.

chaseking123
  • 37
  • 1
  • 7
  • Definitely use `lapply` instead of `for` so your results will be in a list. Also `:` between strings doesn't work; use the variable you stored them in. – alistaire Oct 22 '16 at 02:49

2 Answers2

0

You'd go with for (i in 1:length(a)) { etc } but yeah getting your head around apply functions is generally preferable for speed reasons.

obrl_soil
  • 1,104
  • 12
  • 24
0

Use "" in paste0 function

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" 
Arun kumar mahesh
  • 2,289
  • 2
  • 14
  • 22