Clean way to set up data to map over inputs of different lengths?


#1

I'm trying to set up my data so that I can map a function over inputs of varying lengths. I haven't seen any "clean" ways to do this.

Below is what I'm currently doing. I'm using interaction() to find all the possible combinations of my inputs.

library(tidyverse)

# A bit ugly, but it works
suppressWarnings(interaction(c("shl", "ohl", "whl"), c("2017-2018", "2016-2017"))) %>% 
  levels() %>% 
  str_split("\\.", simplify = TRUE) %>% 
  as_tibble() %>% 
  set_names("league", "season")
#> # A tibble: 6 x 2
#>   league season   
#>   <chr>  <chr>    
#> 1 ohl    2016-2017
#> 2 shl    2016-2017
#> 3 whl    2016-2017
#> 4 ohl    2017-2018
#> 5 shl    2017-2018
#> 6 whl    2017-2018

# What -- for good reason -- doesn't work
c(c("shl", "ohl", "whl"), c("2017-2018", "2016-2017")) %>% 
  levels() %>% 
  str_split("\\.", simplify = TRUE) %>% 
  as_tibble() %>% 
  set_names("league", "season")
#> Error: `nm` must be `NULL` or a character vector the same length as `x`

I feel like there has to be a better way to do this, right? Any ideas?


#2

maybe a Cartesian join?

library(tidyverse)

leagues <- data_frame(league = c("shl", "ohl", "whl"))
seasons <- data_frame(season = c("2017-2018", "2016-2017"))

crossing(leagues, seasons)

# A tibble: 6 x 2
#   league season   
#   <chr>  <chr>    
# 1 shl    2017-2018
# 2 shl    2016-2017
# 3 ohl    2017-2018
# 4 ohl    2016-2017
# 5 whl    2017-2018
# 6 whl    2016-2017

#3

Nice!!! Great answer. Thanks @Galangjs. Might try this