r - 在R中的循环中绑定表
问题描述
我正在尝试从 Sports Reference 中提取大量数据。我的编码背景很薄弱,因为我只在几个过程中自学。我已经弄清楚如何使用 htmltab() 函数从 SR 中提取数据,并且可以从网站上的每个页面创建一个表格。
我的问题是最后合并表格。我知道下面的代码只使用了 5 页,并且使用 rbind() 很容易组合,但这只是一个小测试示例。
我最终将有数千个表要组合,因此最后手动 rbind 是不切实际的。有没有办法在循环的每一步将每个新表附加到某个复合表(或者在最后轻松绑定它们而无需输入数千个表)?
或者,如果我可以将所有数据合并到一个表中,而不必先制作一千个数据似乎更有效,但我不知道该怎么做(显然)。
任何帮助表示赞赏!
(对于那些不熟悉 SR 的人,该网站将他们的表格按 100 个元素分组,因此 i*100 并粘贴到 URL 的第一部分)
for (i in 1:5) {
a <- i*100
url <- paste("https://www.sports-reference.com/cfb/play-index/pgl_finder.cgi?request=1&match=game&year_min=&year_max=&conf_id=&school_id=&opp_id=&game_type=&game_num_min=&game_num_max=&game_location=&game_result=&class=&c1stat=rush_att&c1comp=gt&c1val=0&c2stat=rec&c2comp=gt&c2val=0&c3stat=punt_ret&c3comp=gt&c3val=0&c4stat=kick_ret&c4comp=gt&c4val=0&order_by=date_game&order_by_asc=&offset=",a,sep = "")
nam <- paste("ploop",i,sep = "")
assign(nam,htmltab(url))
??????
}
解决方案
在这种情况下,通常最好将结果存储在列表中,而不是使用assign
. 这里我们将循环的每次迭代的结果存储在一个列表中,然后使用do.call
withrbind
创建单个数据框:
rm(list = ls())
library(htmltab)
tables <- list()
for (i in 1:5) {
a <- i*100
url <- paste("https://www.sports-reference.com/cfb/play-index/pgl_finder.cgi?request=1&match=game&year_min=&year_max=&conf_id=&school_id=&opp_id=&game_type=&game_num_min=&game_num_max=&game_location=&game_result=&class=&c1stat=rush_att&c1comp=gt&c1val=0&c2stat=rec&c2comp=gt&c2val=0&c3stat=punt_ret&c3comp=gt&c3val=0&c4stat=kick_ret&c4comp=gt&c4val=0&order_by=date_game&order_by_asc=&offset=",a,sep = "")
tables[[i]] <- htmltab(url)
}
table.final <- do.call(rbind, tables)
str(table.final)
'data.frame': 520 obs. of 20 variables:
$ Rk : chr "101" "102" "103" "104" ...
$ Player : chr "Myles Gaskin" "Willie Gay" "Jake Gervase" "Kyle Gibson" ...
$ Date : chr "2019-01-01" "2019-01-01" "2019-01-01" "2019-01-01" ...
$ G# : chr "14" "13" "13" "13" ...
$ School : chr "Washington" "Mississippi State" "Iowa" "Central Florida" ...
$ V2 : chr "N" "N" "N" "N" ...
$ Opponent : chr "Ohio State" "Iowa" "Mississippi State" "Louisiana State" ...
$ V2.1 : chr "L" "L" "W" "L" ...
$ Rushing >> Att : chr "24" "0" "0" "0" ...
$ Rushing >> Yds : chr "121" "0" "0" "0" ...
$ Rushing >> TD : chr "2" "0" "0" "0" ...
$ Receiving >> Rec: chr "3" "0" "0" "0" ...
$ Receiving >> Yds: chr "-1" "0" "0" "0" ...
$ Receiving >> TD : chr "0" "0" "0" "0" ...
$ Kick Ret >> Ret : chr "0" "0" "0" "0" ...
$ Kick Ret >> Yds : chr "0" "0" "0" "0" ...
$ Kick Ret >> TD : chr "0" "0" "0" "0" ...
$ Punt Ret >> Ret : chr "0" "0" "0" "0" ...
$ Punt Ret >> Yds : chr "0" "0" "0" "0" ...
$ Punt Ret >> TD : chr "0" "0" "0" "0" ...
推荐阅读
- kubernetes - Kubernetes 在所有 php-fpm pod 上执行命令
- ios - startRangingBeaconsSatisfying约束多个信标
- git - git rebase 在已经合并后到不同的分支
- r - 关于从 COVID19 WHO 数据集生成条形图的问题
- reactjs - 组件仅在包装在 `div` 中时才会更新
- php - 如何在laravel中获取选择框的多个选定值?
- machine-learning - 如何改进消费者支出调查的预测?
- java - 为什么在 Maven 中添加依赖项会触发功能?
- sql - 错误:表“p”缺少 FROM 子句条目
- html - 溢出-x:自动创建不需要的垂直滚动条