I'm having trouble setting names to a df that I have scraped from a website. The html_table has a bunch of columns that don't have proper column names. When I go to use purrr::set_names I get an error message since the columns scraped, are a different length than the columns on the html_table. Is there a way to resolve this that anyone can think of? The missing set of columns appear to be duplicate data. They are identical to columns 5:10 in data. Example below:
library(tidyverse)
# url
url <- "https://legacy.baseballprospectus.com/pitchfx/leaderboards/index.php?hand=&reportType=avg&prp=P&month=&year=2019&pitch=FS&ds=&lim=0"
# get page from URL
page <-
url %>%
xml2::read_html()
# get df from page
data <-
page %>%
rvest::html_table(fill = TRUE) %>%
.[[2]] %>%
data.frame(stringsAsFactors = FALSE) %>%
tbl_df()
# get column names
names <-
page %>%
rvest::html_node("thead") %>%
rvest::html_nodes("th") %>%
rvest::html_text() %>%
stringr::str_trim()
# Add Column names since Scrape does not include
df <-
data %>%
purrr::set_names(names)
#> `nm` must be `NULL` or a character vector the same length as `x`
Created on 2019-10-18 by the reprex package (v0.3.0)