Home > other >  How to get the cartesian product in R?
How to get the cartesian product in R?

Time:02-01

I have a data frame like this:

plazo monto
20 2
50 3

I need to add a rows for values between 1 to the value of plazo and expand my dataframe like below;

plazo monto Semana
20 2 1
20 2 2
20 2 3
20 2
20 2 20
50 3 1
50 3 2
50 3 3
50 3
50 3 50

CodePudding user response:

We can create a nested column with values from 1:plazo for each row and then unnest that column.

df1 <- data.frame(plazo = c(2, 5), monto = c(2,3))

library(tidyverse)

df1 %>% 
  rowwise() %>% 
  mutate(Semana = list(1:plazo)) %>% 
  unnest(Semana)

#> # A tibble: 7 x 3
#>   plazo monto Semana
#>   <dbl> <dbl>  <int>
#> 1     2     2      1
#> 2     2     2      2
#> 3     5     3      1
#> 4     5     3      2
#> 5     5     3      3
#> 6     5     3      4
#> 7     5     3      5

CodePudding user response:

We may use uncount

library(dplyr)
library(tidyr)
df1 %>% 
   uncount(plazo, .id = 'Semana', .remove = FALSE)

-output

  plazo monto Semana
1     2     2      1
2     2     2      2
3     5     3      1
4     5     3      2
5     5     3      3
6     5     3      4
7     5     3      5
  • Related