Add rows until today's date in R

Viewed 126

So i have this kind of R data frame, with only one obs :

date company
2017-08-18 Apple

Desired output

I'd like to add rows until today's date :

date company
2017-08-18 Apple
2017-08-19 Apple
2017-08-20 Apple
. .
. .
. .
2021-05-26 Apple

So that every time the code is launched, it's completed with the actual date. Is it possible ? And if yes, is it possible to automate this as a function so that i can apply it to all of my datasets with this form with a few lines of code only ?

UPDATE

How to do the same when there is more than one date in the data frame, such as :

date comapny
2021-05-24 AMZ
2021-05-25 AMZ
1 Answers

We can create a sequence of dates by specifying the from, to, and by in seq, and wrap with data.frame and the 'company' column extracted from the data (as it is already specified a single row - it gets recycled)

date <- seq(as.Date(df1$date), Sys.Date(), by = '1 day')
data.frame(date, company = df1$company)

If there are more than one row, an option is to either use rowwise

library(dplyr)
library(tidyr)
df1 %>%
   mutate(date = as.Date(date)) %>%
   rowwise %>%
   mutate(date = list(seq(date, Sys.Date(), by = '1 day'))) %>%
   ungroup %>%
   unnest(date)

Or with map

library(purrr)
df1 %>%
    mutate(date = map(as.Date(date), ~ seq(.x, Sys.Date(), by = '1 day'))) %>%
    unnest(date)  

Or may also use complete

df1 %>%
   group_by(company) %>%
   complete(date = seq(min(as.Date(date)), Sys.Date(), by = '1 day'))     
Related