r - 用 R 中的 rvest 刮取一个表标题不匹配的表
问题描述
我正在尝试刮掉这张看起来超级简单的桌子。这是表格的网址:https ://fantasy.nfl.com/research/scoringleaders?position=1&sort=pts&statCategory=stats&statSeason=2019&statType=weekStats&statWeek=1
这是我编码的内容:
url <- "https://fantasy.nfl.com/research/scoringleaders?position=1&sort=pts&statCategory=stats&statSeason=2019&statType=weekStats&statWeek=1"
x = data.frame(read_html(url) %>%
html_nodes("table") %>%
html_table())
这工作正常,但给出了非常奇怪的两行标题,当我尝试添加 %>% slice(-1) 以取出第一行时,它说我不能,因为它是一个列表。真的很想弄清楚如何做到这一点。
解决方案
这是一个解决方案。下面是一个解释。
library(rvest)
library(tidyverse)
read_html(url) %>%
html_nodes("table") %>%
html_table(header = T) %>%
simplify() %>%
first() %>%
setNames(paste0(colnames(.), as.character(.[1,]))) %>%
slice(-1)
输出glimpse()
:
Observations: 25
Variables: 16
$ Rank <chr> "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"…
$ Player <chr> "Lamar Jackson QB - BAL", "Dak Prescott QB - DAL", "Deshaun W…
$ Opp <chr> "@MIA", "NYG", "@NO", "@ARI", "@JAX", "@PHI", "PIT", "WAS", "…
$ PassingYds <chr> "324", "405", "268", "385", "378", "380", "341", "313", "248"…
$ PassingTD <chr> "5", "4", "3", "3", "3", "3", "3", "3", "3", "3", "2", "2", "…
$ PassingInt <chr> "-", "-", "1", "-", "-", "-", "-", "-", "-", "1", "1", "1", "…
$ RushingYds <chr> "6", "12", "40", "22", "2", "-", "-", "5", "24", "6", "13", "…
$ RushingTD <chr> "-", "-", "1", "-", "-", "-", "-", "-", "-", "-", "-", "-", "…
$ ReceivingRec <chr> "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "…
$ ReceivingYds <chr> "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "…
$ ReceivingTD <chr> "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "…
$ RetTD <chr> "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "…
$ MiscFumTD <chr> "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "…
$ Misc2PT <chr> "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "1", "-", "…
$ FumLost <chr> "-", "-", "-", "1", "-", "-", "-", "-", "-", "-", "-", "-", "…
$ FantasyPoints <chr> "33.56", "33.40", "30.72", "27.60", "27.32", "27.20", "25.64"…
来自?html_table
文档的解释:
html_table
目前做了一些假设:
- 没有单元格跨越多行
- 标题在第一行
你的部分问题是通过设置解决header = TRUE
的html_table()
。
问题的另一部分是标题单元格跨越两行,这html_table()
是不期望的。
假设您不想丢失任一标题行中的信息,您可以:
- 使用
simplify
andfirst
从您获得的列表中提取数据框html_table
- 用于
setNames
合并两个标题行(现在是数据框列和第一行) - 删除第一行(现在是多余的)
slice
推荐阅读
- c++ - OpenCV 3.4.3 中对“cv::String::deallocate()”错误的未定义引用
- adobe - 工作流超时功能在 aem 中不起作用
- recursion - OCaml 函数来评估加法和减法
- android - Firebase Authentication Android:删除任何经过身份验证的用户
- python - Pandas Dataframe 数据是相同的还是新的?
- javascript - 反应:e.target.getAttribute ("id") 工作 20% 的时间?
- python - 如何在 django rest 框架中获取外键字段名称而不是 id
- ibm-cloud-infrastructure - 软层:如何使用 golang 将 vlan 添加到服务器
- c - 在 C 中记录和替换文本文件中的变量
- java - 使用 BigDecimals 计算百分比