rpivottidyverseexpand

how expand pivoted dataframe?


I want to get combination of all parameters after pivoting data frame. I have data frame like this:

df <- data.frame(parameter = c(rep("X",5), rep("Y",3)), value=c(letters[1:5],1:3))

I do the following transformation:

df %>% 
  group_by(parameter) %>%
  mutate(row = row_number()) %>%
  pivot_wider(names_from = parameter, values_from = value) %>%
  select(-row)

my output is:

# A tibble: 5 x 2
  X     Y    
  <chr> <chr>
1 a     1    
2 b     2    
3 c     3    
4 d     NA   
5 e     NA   

my desired output:

# A tibble: 15 x 2
   X         Y
   <fct> <int>
 1 a         1
 2 b         1
 3 c         1
 4 d         1
 5 e         1
 6 a         2
 7 b         2
...
14 d         3
15 e         3

Solution

  • Heres a solution based on the expand.grid function.

    df %>% 
      group_by(parameter) %>%
      mutate(row = row_number()) %>%
      pivot_wider(names_from = parameter, values_from = value) %>%
      select(-row) %>%
      expand.grid() %>%
      filter(!is.na(Y))
    

    It's a rather dirty workaround, I'm sure there's another, more beautiful way.