0

I have the following input data :

dates1 <- data.frame(datess = seq(as.Date('2020-05-01'),as.Date('2020-11-01'),by = "1 month"),Sales = 1)
category <- data.frame(cat=c("a","b","c"))

How do I achieve the following :

enter image description here

Let's Code
  • 99
  • 7

2 Answers2

1

You can use crossing

tidyr::crossing(dates1, category)

# A tibble: 21 x 3
#   datess     Sales cat  
#   <date>     <dbl> <chr>
# 1 2020-05-01     1 a    
# 2 2020-05-01     1 b    
# 3 2020-05-01     1 c    
# 4 2020-06-01     1 a    
# 5 2020-06-01     1 b    
# 6 2020-06-01     1 c    
# 7 2020-07-01     1 a    
# 8 2020-07-01     1 b    
# 9 2020-07-01     1 c    
#10 2020-08-01     1 a    
# … with 11 more rows

Or expand_grid

tidyr::expand_grid(dates1, category)
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
1

Base R solution:

setNames(do.call("rbind", lapply(category, cbind, dates1)), c("category", names(dates1)))

Data:

dates1 <- data.frame(datess = seq(as.Date('2020-05-01'),as.Date('2020-11-01'),by = "1 month"),Sales = 1)
category <- c("a", "b", "c")
hello_friend
  • 5,682
  • 1
  • 11
  • 15