rdataframedplyrpurrrrep

Repeating a vector of names in a column over each date


I want to assign each letter from the vectors to each date, thus resulting in duplicating the dates.

date_range <- seq(from = as.Date("01/01/2015", "%d/%m/%Y"), to = as.Date("01/12/2021", "%d/%m/%Y"), by = "month")
DF <- data.frame(date = date_range, Source = map(c("a", "b", "c", "d"), rep, length.out = length(date_range)))

This results in repeating the letters into their own columns which is now what I am trying do to. The perfect example would be:

  date       Source
1 01/01/2015      a
2 01/01/2015      b
3 01/01/2015      c
4 01/01/2015      d
5 02/01/2015      a

Let me know if there's any more info I can provide!


Solution

  • Don't use map; you can take advantage of vector recycling. Just repeat each element of date_range 4 times.

    DF <- data.frame(date = rep(date_range, each = 4), 
                     Source = c("a", "b", "c", "d"))
    
    head(DF)
              date Source
    1   2015-01-01      a
    2   2015-01-01      b
    3   2015-01-01      c
    4   2015-01-01      d
    5   2015-02-01      a
    6   2015-02-01      b
    7   2015-02-01      c
    8   2015-02-01      d
    9   2015-03-01      a
    10  2015-03-01      b
    

    Another option with tidyr::separate_rows:

    library(tidyr)
    data.frame(date = date_range, Source = c("a,b,c,d")) %>% 
      separate_rows(Source)