Search code examples
rtidyverse

creating combinations in a dataframe in R


In R, I have a dataframe defined by

foo <- data.frame(variable = c("peltrawl_PF","peltrawl_DF"),low = c(0,3.8),high = c(10,11))

I want to make it look like the dataframe

bar <- data.frame(peltrawl_PF = c(0,0,10,10),peltrawl_DF = c(3.8,11,3.8,11)).

I can do this using this simple case:

foo <- foo %>% mutate(row = row_number()) %>% 
  pivot_longer(cols = c(low, high), names_to = "measure") %>%
  pivot_wider(names_from = variable, values_from = value) %>%
  select(-measure)

bar <- expand.grid(peltrawl_PF = unique(foo$peltrawl_PF), peltrawl_DF = unique(foo$peltrawl_DF)) %>% 
  na.omit()

But I have to define the variable names which go into expand.grid here, which I don't want to do. This code will be used on a dataframe which is 132x3 which I will be reading in from a csv file, so defining all these variables names in expand.grid is not viable.


Solution

  • Without specifying the actual variable names you can do -

    library(dplyr)
    library(tidyr)
    
    foo %>% 
      pivot_longer(cols = -variable, names_to = "measure") %>%
      pivot_wider(names_from = variable, values_from = value) %>%
      select(-measure) %>%
      do.call(expand_grid, .)
    
    #  peltrawl_PF peltrawl_DF
    #        <dbl>       <dbl>
    #1           0         3.8
    #2           0        11  
    #3          10         3.8
    #4          10        11