【发布时间】:2016-01-25 22:25:09
【问题描述】:
我正在尝试编写一个循环来对我通过公式提供的连续日期列表执行readHTMLTable()。我已成功导入日期之间的所有数据。但是,该数据没有日期列,因此使用我提供循环的日期序列,我希望循环读取 HTMLTable,然后添加一个带有用于该迭代的日期的新列。
这是我目前所拥有的:
library(XML)
library(RCurl)
library(plyr)
# create the days
x <- seq(as.Date("2015-04-10"), as.Date("2015-04-15"), by = "day")
# create a url template for sprintf()
utmp <- "http://www.basketball-reference.com/friv/dailyleaders.cgi?month=%d&day=%d&year=%d"
# convert to numeric matrix after splitting for year, month, day
m <- do.call(rbind, lapply(strsplit(as.character(x), "-"), type.convert))
# create the list to hold the results
tables <- vector("list", length(m))
# get the tables
for(i in seq_len(nrow(m))) {
# create the url for the day and if it exists, read it - if not, NULL
tables[[i]] <- if(url.exists(u <- sprintf(utmp, m[i, 2], m[i, 3], m[i, 1])))
readHTMLTable(u, stringsAsFactors = FALSE)
else NULL
}
data <- ldply(tables,data.frame)
因此,基本上,我希望我的最终数据框以 m 为新列,名为 data$Date。
感谢您的帮助,如果您需要任何说明,请告诉我!
【问题讨论】:
-
如果循环中没有
Sys.sleep,则违反了网站的terms of service。
标签: xml r web-scraping rcurl