如何在循环中填充部分URL

时间:2012-11-27 23:29:06

标签: r

  

可能重复:
  Read multiple CSV files into separate data frames

如何用for循环填充部分URL,我尝试了一个有效的URL,例如:

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

但是当我将代码更改为循环时,它失败了:

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="|")
}

2 个答案:

答案 0 :(得分:3)

问题是您的迭代器i在引号内,因此未按预期进行评估。使用paste0(.)


此外,您可能希望变量data与列表类似。也许不叫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="|")
}

编辑(mnel)

或更具惯用力

urls <-paste0("http://somelink.php?station=",station, "&start=", Year, "01-01&etc")
myData <- lapply(urls, read.table, header = TRUE, sep = '|')

答案 1 :(得分:1)

我偏爱sprintf函数,因为很容易看到最终字符串的样子:

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="|")
}