How can I ignore a case of a logical list throwing an error in R programming?

44 views Asked by At

I'm trying to combine lists of statistics scraped from the NCAA Baseball website into a table with bind_rows. One of my tables is returning a list of logical operators because one of the teams I'm pulling doesn't have statistics yet for this year. I would like to ignore the case of a list being empty so I can continue with combining the other lists into the table.

Here is my code:

library(baseballr)
library(tidyverse)

d3_schools <- load_ncaa_baseball_teams() %>% 
  dplyr::filter(division == 3, year == 2024, conference == "AMCC")

safe_ncaa_scrape <- purrr::safely(ncaa_scrape)

team_stats <- function(teamid, team, type) {
  if (type == "batting") {
    message(paste("Getting batting stats for ", team))
    stats <- safe_ncaa_scrape(team_id = teamid, year = 2024, type = "batting")
  } else {
    message(paste("Getting pitching stats for ", team))
    stats <- safe_ncaa_scrape(team_id = teamid, year = 2024, type = "pitching")
  }
  
  Sys.sleep(sample(seq(.005,.02,.001),1))
  
  return(stats)
}

batting_stats <- 1:nrow(d3_schools) %>% 
  purrr::map(function(x) team_stats(d3_schools$team_id[[x]],
                                    d3_schools$team_name[[x]],
                                    type = "batting"))

pitching_stats <- 1:nrow(d3_schools) %>% 
  purrr::map(function(x) team_stats(d3_schools$team_id[[x]],
                                    d3_schools$team_name[[x]],
                                    type = "pitching"))

d3_pitching <- pitching_stats %>%
  map("result") %>% bind_rows()

d3_pitching <- pitching_stats %>%
    map("result") %>% bind_rows()

Here is the error I'm receiving: Error in bind_rows(): ! Can't combine ..4$Yr<character> and..5$Yr <logical>.

1

There are 1 answers

0
zephryl On

You can use purrr::discard() to remove dataframes where Yr is logical:

library(dplyr)
library(purrr)

d3_pitching <- pitching_stats %>%
  map("result") %>% 
  discard(\(dat) is.logical(dat$Yr)) %>%
  bind_rows()