Get the existing mlbids

extant_mlb <- read.csv(
  file.path('..', 'data-raw', 'mlbids.csv'),
  stringsAsFactors = FALSE
)

id_type <- 'mlb'

Limit to only missing dob

mask <- lapply(extant_mlb$dob, function(x) nchar(x) == 0) %>% unlist()

extant_mlb <- extant_mlb[mask, ]

Loop over and read

extant_mlbids <- extant_mlb$mlbid %>% sort()

verbose <- TRUE
players <- list()

for (i in extant_mlbids) {
  if (verbose) cat(paste0(i,'...'))
  tryCatch({
    m <- do.call(mlb, list('id' = i))
    players[[paste0('p', i)]] <- m
    if (verbose) cat(paste(m$name), m$dob, '\n')
  }, error = function(e) {
    cat("failed on", i, '|', conditionMessage(e), "\n")
  })
}

#bind rows
sprintf('read %s new players from %s.com!', length(players), id_type)
new_ids <- dplyr::bind_rows(players)

extant_mlb <- anti_join(extant_mlb, new_ids, by = 'mlbid')
#bind extant and new
final <- rbind(extant_mlb, new_ids)

write.csv(final, file = sprintf(file.path('..', 'data-raw', '%sids.csv'), 'mlb'), row.names = FALSE)


almartin82/mlbids documentation built on May 10, 2019, 9:54 a.m.