r - 如何在 R 中读取多个 HTML 表

标签 r

我正在尝试自动提取并保存到此 readHTML 函数的数据框;我是一名 R 新手,无法弄清楚如何编写一个循环来自动执行此函数,如果您逐一执行该函数,该函数就可以工作。

library('XML')

urls<-c("http://www.basketball-reference.com/teams/ATL/","http://www.basketball-reference.com/teams/BOS/")
theurl<-urls[2] #Pick second link (celtics)

tables <- readHTMLTable(theurl)
n.rows <- unlist(lapply(tables, function(t) dim(t)[1]))
BOS <-tables[[which.max(n.rows)]] 
Team.History<-write.csv(BOS,"Bos.csv")

任何和所有帮助将不胜感激!

最佳答案

我认为这结合了两个答案中最好的(并且整理了一点)。

library(RCurl)
library(XML)

stem <- "http://www.basketball-reference.com/teams/"
teams <- htmlParse(getURL(stem), asText=T)
teams <- xpathSApply(teams,"//*/a[contains(@href,'/teams/')]", xmlAttrs)[-1]
teams <- gsub("/teams/(.*)/", "\\1", teams)
urls <- paste0(stem, teams)

names(teams) <- NULL   # get rid of the "href" labels
names(urls) <- teams

results <- data.frame()
for(team in teams){
   tables <- readHTMLTable(urls[team])
   n.rows <- unlist(lapply(tables, function(t) dim(t)[1]))
   team.results <- tables[[which.max(n.rows)]] 
   write.csv(team.results, file=paste0(team, ".csv"))
   team.results$TeamCode <- team
   results <- rbind(results, team.results)
   rm(team.results, n.rows, tables)
}
rm(stem, team)

write.csv(results, file="AllTeams.csv")

关于r - 如何在 R 中读取多个 HTML 表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11803774/

相关文章:

r - R 中系统计算奇异 : reciprocal condition number=. .. 是否有解决方案?

R ggplot2 : colouring step plot depending on value

r - 创建列联表

python - 如何在R中编写fftshift和ifftshift?

r - 如何将 R 包快照到 Packrat?

c++ - NumericMatrix 未被识别为 RcppParallel 包中的类型

r - 将所有内核与 Microsoft R Open 和 Google Compute Engine 结合使用

r - 无法更改 ggplot2 直方图上的颜色

r - 从 ctree 对象中提取预测变量

r - 加快 R 中的概率加权采样