如何忽略 R 编程中逻辑列表抛出错误的情况?

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

我正在尝试将从 NCAA 棒球网站上抓取的统计数据列表合并到带有 bind_rows 的表中。我的一个表正在返回逻辑运算符列表,因为我正在拉动的一个团队还没有今年的统计数据。我想忽略列表为空的情况,以便我可以继续将其他列表组合到表中。

这是我的代码:

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()

这是我收到的错误:

Error in 
bind_rows()
: ! Can't combine 
..4$Yr
<character> and
..5$Yr
 <logical>.

r list try-catch logical-operators
1个回答
0
投票

您可以使用

purrr::discard()
删除
Yr
符合逻辑的数据框:

library(dplyr)
library(purrr)

d3_pitching <- pitching_stats %>%
  map("result") %>% 
  discard(\(dat) is.logical(dat$Yr)) %>%
  bind_rows()
© www.soinside.com 2019 - 2024. All rights reserved.