2016-01-25 43 views
0

我正在嘗試編寫一個循環來執行readHTMLTable(),通過公式提供的連續日期列表。我已成功導入日期之間的所有數據。但是,該數據並不包含日期列,因此使用我提供循環的日期序列,我希望循環讀取HTML表格,然後添加一個新列以及用於該迭代的日期。在日期列表中使用readHTMLTable並使用數據創建新日期列

這是我到目前爲止有:

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新列。

感謝您的幫助,如果您需要澄清,請告訴我!

+0

如果循環中沒有'Sys.sleep',那麼您違反了網站的[服務條款](http://www.sports-reference.com/termsofuse.shtml)。 – hrbrmstr

回答

1

考慮使用mapply()(apply系列的多元函數),其中您傳遞日期,網址和表格迭代器列表以下載html表格。您可以避免矩陣處理,因爲format()可以提取部分日期類型。此外,請考慮不要將NULL用於不存在的URL,因爲它可能以後不會綁定。只需過濾掉空的元素。

# LIST OF DATES 
x <- lapply(0:5, function(i) as.Date("2015-04-10")+i)  

# LIST OF URLS 
utmp <- "http://www.basketball-reference.com/friv/dailyleaders.cgi?month=%d&day=%d&year=%d" 
urlist <- c(lapply(x, function(i) sprintf(utmp, as.numeric(format(i, '%m')), 
               as.numeric(format(i, '%d')), 
               as.numeric(format(i, '%y'))))) 

# USER DEFINED FUNCTION 
tables <- vector("list", length(x)) 
tabledwnld <- function(dt, url, i) {      
        if (url.exists(url)) { 
         tableNodes <- readHTMLTable(url)      
         tables[[i]] <- tableNodes[[1]] 
         tables[[i]]['Date'] <- dt 
         return(tables) 
        } 
       } 
# APPLY ABOVE FUNCTION (RETURNS LARGE MATRIX OF TABLES) 
data <- mapply(tabledwnld, x, urlist, 1:6) 

# BIND TO DATA FRAME 
finaldata <- do.call(rbind, data) 

另外,請留意@ hrbrmstr在註釋中的警告,下面的網站顯示如下。您可能需要的空間你的表格下載:

除本款明確規定,您同意不 使用或啓動任何自動化系統,包括但不限於, 機器人,蜘蛛,離線閱讀器,或類似通過使用傳統的在線Web瀏覽器 來讀取在任何給定時間段內發送更多請求消息到站點服務器的方式訪問 站點的方式,該方式比典型人類通常在 產生的同一時間段,查看和提交材料。

+0

嘿,謝謝你願意幫忙。不幸的是,在我的結尾你的代碼是不可重現的。我在'tabledwnld'函數中收到一個關於意外符號的錯誤,另一個錯誤是關於無法找到'readHTMLTable'的繼承方法,關於無效類型/長度的循環的'dt'部分的錯誤(閉包/ 0)進行向量分配,然後最後出現一些關於意外「}」的錯誤。任何想法,爲什麼我會看到這些在我的目的? – medavis6

+0

查看更新。 「if」語句沒有正確包裹在圓括號中。此外,XML庫的[readHTMLTable](http://www.inside-r.org/packages/cran/xml/docs/readhtmltable)不會直接創建數據框,而是檢索URL解析的'

'節點集。 – Parfait

+0

謝謝!代碼現在全部運行。然而,我仍然有一個問題,'tables'命令返回一個0列表,然後'data'命令返回0 obs。 0個變量。 – medavis6