inserting a tibble before and after each row in another tibble

library(tidyverse)

insert_df <- tibble(
  arena = as.character("PBO"),
  home = as.character("NA"),
  visitor = as.character("PBO")
)

games <- tibble(
  arena = c("NB", "SBY", "OSH"),
  home = c("NB", "SBY", "OSH"),
  visitor = c("PBO", "PBO", "PBO")
)

I would like to get the result as shown below. I have tried spliting the games tibble into a list and add_row() to no avail. Thanks.

output <- tibble(
  arena = c("PBO", "NB", "PBO", "PBO", "SBY", "PBO", "PBO", "OSH", "PBO"),
  home = c("NA", "NB", "NA", "NA", "SBY", "NA", "NA", "OSH", "NA"),
  visitor = c("PBO", "PBO", "PBO", "PBO", "PBO", "PBO", "PBO", "PBO", "PBO")
)

Hi @turkjr19 ,
I'm sure there's a more concise approach, but here's one solution.

library("dplyr")
#> 
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#> 
#>     filter, lag
#> The following objects are masked from 'package:base':
#> 
#>     intersect, setdiff, setequal, union

insert_df <- tibble(
  arena = as.character("PBO"),
  home = as.character("NA"),
  visitor = as.character("PBO")
)

games <- tibble(
  arena = c("NB", "SBY", "OSH"),
  home = c("NB", "SBY", "OSH"),
  visitor = c("PBO", "PBO", "PBO")
)

# Function to bind the insert_df before and after each row
add_insert <- function(x) {
  bind_rows(insert_df, x, insert_df)
}

# Add row id for grouping and modifying the group
games <- games %>%
  mutate(id = seq(nrow(.)))

games_w_insert <- games %>%
    group_by(id) %>%
    group_modify(.f = ~add_insert(.x)) %>%
    ungroup() %>%
    select(-id)

output <- tibble(
  arena = c("PBO", "NB", "PBO", "PBO", "SBY", "PBO", "PBO", "OSH", "PBO"),
  home = c("NA", "NB", "NA", "NA", "SBY", "NA", "NA", "OSH", "NA"),
  visitor = c("PBO", "PBO", "PBO", "PBO", "PBO", "PBO", "PBO", "PBO", "PBO")
)

identical(games_w_insert, output)
#> [1] TRUE

Created on 2021-10-01 by the reprex package (v2.0.1)

Thank you Jim. Your solution works nicely.

This topic was automatically closed 7 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.