删除R中RVest的表标题不匹配的表

问题描述 投票:0回答:1

我正在尝试刮擦这张桌子,这看起来会非常简单。这是表格的网址: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)以取出第一行时,它说我不能,因为它是一个列表。真的很想弄清楚该怎么做。

r web-scraping rvest
1个回答
0
投票

这里是一个解决方案。解释如下。

library(rvest)
library(tidyverse)

read_html(url) %>% 
  html_nodes("table") %>%  
  html_table(header = T) %>%
  simplify() %>% 
  first() %>% 
  setNames(paste0(colnames(.), as.character(.[1,]))) %>%
  slice(-1) 

[C0的输出:

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()所不希望的。

假设您不想丢失任一标题行中的信息,则可以:

  1. 使用html_table()simplify从您从first获得的列表中拉出数据帧
  2. 使用html_table合并两个标题行(现在是数据框列和第一行)
  3. 使用setNames删除第一行(现在是多余的)
© www.soinside.com 2019 - 2024. All rights reserved.