1

I want to change the slots' structure, from character to integer, and still keep multiple values in a cell.

The df below shows some of the game constraints (timetabling). i.e. Row 2 states that team 6 can play (at most) 2 away (mode) games during the time slots 8, 11, 25, and 29.

enter image description here

Phil
  • 7,287
  • 3
  • 36
  • 66
  • 1
    You can set up the `slots` variable as a list, but it gets fairly annoying to manipulate. One potential solution is to turn your data to long such that rows are duplicated as many times are there are values in that variable. – Phil Mar 06 '21 at 16:38

1 Answers1

2

As Phill said, you can use str_split() to split the string into a character vector, but your column becomes a list, but I would'nt either recommend using that. Or you can separate_rows() which I find easier to work with.

library(tidyverse)

test <- tibble(mode = c("A", "A", "B", "B"),
               slots = c("17", "8;11;25;29", "19", "14;22"))

test
#> # A tibble: 4 x 2
#>   mode  slots     
#>   <chr> <chr>     
#> 1 A     17        
#> 2 A     8;11;25;29
#> 3 B     19        
#> 4 B     14;22
test %>% 
    mutate(slots = str_split(slots, pattern = ";"))
#> # A tibble: 4 x 2
#>   mode  slots    
#>   <chr> <list>   
#> 1 A     <chr [1]>
#> 2 A     <chr [4]>
#> 3 B     <chr [1]>
#> 4 B     <chr [2]>
test %>% 
    separate_rows(slots, sep = ";")
#> # A tibble: 8 x 2
#>   mode  slots
#>   <chr> <chr>
#> 1 A     17   
#> 2 A     8    
#> 3 A     11   
#> 4 A     25   
#> 5 A     29   
#> 6 B     19   
#> 7 B     14   
#> 8 B     22

Created on 2021-03-06 by the reprex package (v0.3.0)

Samuel Calderon
  • 641
  • 3
  • 13
  • Yeah, I tried with strsplit, before posting this, but I encountered some new problems when trying to manipulate further. I hoped to avoid making duplicates, but I think I'll just go for that solution for now. Thanks for your help! – S.Network12 Mar 08 '21 at 08:39