Looping through function in R


Using this line of code, I can retrieve ~55 columns of details for each of the 15 games played at the AAA level in professional baseball last Friday, the 31st. Package used here is baseballr.

mlb_game_pks("2023-03-31", level_ids = c(11)) -> AAA

One of the columns of data generated is game_pk which is the unique identifier of the specific game and in the code above, 15 such unique numbers are returned.

My question is how to pass through each of the 15 unique game_pk numbers through this line of code to then pull all of the pitch by pitch data?

mlb_pbp_diff(game_pk = 722652, start_timecode = "20230331", end_timecode = "20230331") -> pbp_example

Note there may very well be another function in baseballr that will do this automatically by just plugging in the desired date range but I am actually trying to learn a little about looping in R using data I am familiar with.

Tried this to no avail:

Made list of game_pk's: PKs <- list(AAA$game_pk)

for(i in PKs){
mlb_pbp_diff(i, start_timecode = "20230331", end_timecode = "20230331") -> pbp_example

You need to store the output in a list or otherwise accumulate the results rather than overwrite the value as your example does.
I hope this works but I wouldn't be surprised if it needs adjustment.

PKs <- list(AAA$game_pk)
OUT <- vector(mode = "list ", length = length(PKs))

for(i in seq_along(PKs)){
mlb_pbp_diff(PKs[[i]], start_timecode = "20230331", end_timecode = "20230331") -> OUT[[i]]

There are several ways to avoid an explicit loop, such as the *apply family of functions and the map() functions in the purrr package.

As mentioned by @FJCC , you can use map_dfr from purrr package to loop through PKs and combine data into a data frame in one go.


games <- mlb_game_pks("2023-03-31", level_ids = c(11))
pks <- unique(games$game_pk)
result <- map_dfr(pks, function(pk) {
  mlb_pbp_diff(pk, start_timecode = "20230331", end_timecode = "20230331")

This topic was automatically closed 42 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.