0

Possible Duplicate:
Read multiple CSV files into separate data frames

How can I fill part of URL with a for loop, I tried one URL it worked, eg:

data <- read.table("http://somelink.php?station=2&start=2012-01-01&etc", header=T,sep="|")

But when I changed the code into a loop, it failed:

station <- c(1:10)
Year <- format(Sys.time(), "%Y")

for (i in station){
data <- read.table("http://somelink.php?station=i&start=Year-01-01&etc", header=T,sep="|")
}
Community
  • 1
  • 1
Rosa
  • 1,793
  • 5
  • 18
  • 23

2 Answers2

3

The problem is that your iterator i is inside the quotation marks and hence not being evaluated as intended. use paste0(.)


Also, you may want your variable data to be list-like. And perhaps not called data.

myData <- list(length = length(station))
for (i in station){
  urli <- paste0("http://somelink.php?station=", i, "&start=Year-01-01&etc")
  myData[[i]] <- read.table(urli, header=T,sep="|")
}

Edit (mnel)

or more idiomatically

urls <-paste0("http://somelink.php?station=",station, "&start=", Year, "01-01&etc")
myData <- lapply(urls, read.table, header = TRUE, sep = '|')
mnel
  • 113,303
  • 27
  • 265
  • 254
Ricardo Saporta
  • 54,400
  • 17
  • 144
  • 178
  • THANK YOU!The station gets running, but I didn't realize that couple of the stations have no data would result in an error, is there a way that can fix the error "no lines available in input"?? – Rosa Nov 28 '12 at 19:11
  • @rosa can you `dput(urls)` and post it, perhaps in another question? – Ricardo Saporta Nov 28 '12 at 19:31
  • @mnel,@Ricardo Saporta,I'm not sure if I understand the dput(urls) part, but I rewrited and posted another question, thanks – Rosa Nov 28 '12 at 19:54
  • @Rosa if you `dput()` an R object, you'll get a string that someone else can paste into their R console to create that object. So if you paste the result of `dput(urls)` into your Stack Overflow question, it makes it a lot easier for people to help you. – Gregor Thomas Dec 03 '12 at 22:32
1

I'm partial to the sprintf function because it's easy to see what the final string will look like:

station_data <- list()
for (i in station) {
  station_data[[i]] <- read.table(sprintf("http://somelink.php?station=%s&start=Year-01-01&etc", i), 
    header=TRUE, sep="|")
}
Erik Shilts
  • 4,389
  • 2
  • 26
  • 51