1

I'm looking to create a data frame that has all of the possible combinations from only one data frame (b).

Here is a reproducible example:

a <- data.frame(id = c(1, 2),
            indicator = c('a', 'a'))

b <- data.frame(date = c('2020-01-01', '2020-02-01'))

Desired output:

data.frame(id = c(1, 1, 2, 2),
       indicator = c('a', 'a', 'a', 'a'),
       date = c('2020-01-01','2020-01-01', '2020-02-01', '2020-02-01'))

id  indicator date
1   a         2020-01-01        
1   a         2020-01-01        
2   a         2020-02-01        
2   a         2020-02-01

However, when I use the expand.grid function, I receive a nested data frame

expand.grid(a, b)

Failed Attempt

Allan Cameron
  • 147,086
  • 7
  • 49
  • 87
mf17
  • 91
  • 6

1 Answers1

1

I am sure there are smarter ways of doing it. But one option would be to use the pivot_longer() funtion.

>     b <- data.frame(date = c('2020-01-01', '2020-02-01'))
>     a
  id indicator
1  1         a
2  2         a
>     b
        date
1 2020-01-01
2 2020-02-01
>     c<-data.frame(a,b,b)
>     c
  id indicator       date     date.1
1  1         a 2020-01-01 2020-01-01
2  2         a 2020-02-01 2020-02-01
>     d<-pivot_longer(data=c,cols=-c(1:2))
>     e<-d[,-3]
>     e
# A tibble: 4 x 3
     id indicator value     
  <dbl> <fct>     <fct>     
1     1 a         2020-01-01
2     1 a         2020-01-01
3     2 a         2020-02-01
4     2 a         2020-02-01