2016-11-17 116 views
0

我有一段簡單的R代碼,它從一個網站讀取html數據,然後我嘗試遍歷頁面並從每個頁面獲取數據。我已經無數次地使用了這段代碼,它很有用。它將來自每個頁面的結果添加到R變量中,但由於某種原因,它不能工作。有任何想法嗎?R函數將不會修改全局變量

library(XML) 
library(RCurl) 


data <- NULL 

getData <- function(url) { 
#For some reason cant read directly from site, need to use RCurl to get the data first 
xData <- getURL(url) 
table <- data.frame(readHTMLTable(xData)$'NULL') 
data <- table 
} 

getData(url="https://steemdb.com/accounts/reputation?page=1") 
+0

X < - 的getData(URL =「https://steemdb.com/accounts/reputation?page = 1「) x包含數據。 – Indi

+0

如何爲函數添加'return(data)'?我不會建議混合全球環境和功能環境。 –

回答

1

我想我知道什麼是錯

變化data <- tabledata <<- table你的函數

您將結果分配給該函數的局部環境中,而<<-將其分配給全球環境。

我建議您嘗試以下

library(rvest) 
getData <- function(url) { html_table(read_html(url)) } 

data <- getData("https://steemdb.com/accounts/reputation?page=1") 

甚至更​​好

library(rvest) 
getData <- function(url) { html_table(read_html(url)) } 
steemdb.url <-"https://steemdb.com/accounts/reputation?page=" 

data <- lapply(1:100, function(i) getData(paste0(steemdb.url, i))) 
data <- do.call(rbind, data) 
View(data) 

1:100 will get you the first 100 pages. 
+0

感謝dimitris_ps,只是編輯你的代碼do.call(rbind,data)需要做兩次才能工作。謝謝您的幫助。 – Kharoof