0

I have a df as:

enter image description here

How can I convert it into:

enter image description here

I could build a date range between dates as:

Main_Date_Range <- seq(Sdate, Edate,"days")

but not able to figure out how to join and get factors as well.

CodeMaster
  • 431
  • 4
  • 14
  • Please do not post an image of code/data/errors [for these reasons](https://meta.stackoverflow.com/questions/285551/why-not-upload-images-of-code-errors-when-asking-a-question/285557#285557). To share your data, you could type `dput(NAME_OF_DATASET)` into the console and copy & paste the output starting with `structure(....` into your post. – stefan Jan 23 '23 at 21:57

1 Answers1

2

One option would be to use tidyr::expand which requires to convert your dates to proper dates and to add an id column for the grouping:

library(dplyr, warn = FALSE)
library(tidyr)

dat |> 
  mutate(
    across(c(Sdate, Edate), as.Date, format = "%m/%d/%Y"),
    id = row_number()
  ) |> 
  group_by(id) |> 
  expand(entity, date = seq.Date(Sdate, Edate, "day"), factor) |> 
  ungroup() |> 
  select(-id) |> 
  mutate(date = format(date,  "%m/%d/%Y"))
#> # A tibble: 10 × 3
#>    entity date       factor
#>    <chr>  <chr>       <dbl>
#>  1 abc    01/01/2022    0.2
#>  2 abc    01/02/2022    0.2
#>  3 abc    01/03/2022    0.2
#>  4 abc    01/04/2022    0.2
#>  5 abc    01/10/2022    0.5
#>  6 abc    01/11/2022    0.5
#>  7 abc    01/12/2022    0.5
#>  8 abc    01/13/2022    0.5
#>  9 abc    01/14/2022    0.5
#> 10 abc    01/15/2022    0.5

DATA

dat <- data.frame(
  entity = "abc",
  Sdate = c("1/1/2022", "1/10/2022"),
  Edate = c("1/4/2022", "1/15/2022"),
  factor = c(0.2, 0.5)
)
stefan
  • 90,330
  • 6
  • 25
  • 51