Expanding/Appending Dates

I had posted this previously. The code fix (posted below) worked fine until recently. All packages have been update (Tidyr, etc.).

A sample data frame is as follows:

   transaction_id = c("1", "2"),
       trade_date = as.Date(c("2019-07-01", "2019-08-01")),
            start = as.Date(c("2019-08-01", "2019-12-01")),
              end = as.Date(c("2019-10-31", "2020-02-28")),
            price = c(5, 6),
         currency = c("CAD", "CAD"),
           volume = c(10000, 5000)
)

I wanted to expand the dateframe monthly for each transaction from start to end. The proposed code fix below worked fine until recently.

df %>% 
    group_by(transaction_id) %>% 
    mutate(start=list(seq(start, end, "months"))) %>% 
    unnest_longer(c(start)) %>% 
    mutate(end = ceiling_date(start, "month") - 1)

It's now creating the following error:

Error in as.Date.default(value) :
do not know how to convert 'value' to class “Date”

Any suggestions on what has happened, or how to fix this?

Thanks

Does this work for you?

library(dplyr)
library(tidyr)
library(lubridate)

df <- data.frame(
    transaction_id = c("1", "2"),
    trade_date = as.Date(c("2019-07-01", "2019-08-01")),
    start = as.Date(c("2019-08-01", "2019-12-01")),
    end = as.Date(c("2019-10-31", "2020-02-28")),
    price = c(5, 6),
    currency = c("CAD", "CAD"),
    volume = c(10000, 5000)
)

df %>%
    group_by(transaction_id) %>% 
    mutate(start=list(seq(start, end, "months"))) %>% 
    unnest(col=start) %>% 
    mutate(end = ceiling_date(start, "month") - 1)
#> # A tibble: 6 x 7
#> # Groups:   transaction_id [2]
#>   transaction_id trade_date start      end        price currency volume
#>   <chr>          <date>     <date>     <date>     <dbl> <chr>     <dbl>
#> 1 1              2019-07-01 2019-08-01 2019-08-31     5 CAD       10000
#> 2 1              2019-07-01 2019-09-01 2019-09-30     5 CAD       10000
#> 3 1              2019-07-01 2019-10-01 2019-10-31     5 CAD       10000
#> 4 2              2019-08-01 2019-12-01 2019-12-31     6 CAD        5000
#> 5 2              2019-08-01 2020-01-01 2020-01-31     6 CAD        5000
#> 6 2              2019-08-01 2020-02-01 2020-02-29     6 CAD        5000

Created on 2021-01-26 by the reprex package (v0.3.0.9001)

Very helpful. Thanks. I'm am surprised the unnest_longer stopped working. It would seem to be more applicable (i.e., expand the rows with the element list).

Same here. The unnest_longer() worked fine for a while then it stopped. No other code changes, so I was a little baffled. Perhaps a package update issue?

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.

Hello, if i using unnest() all works, but when i using unnest_longer() i get do not know how to convert 'value' to class “Date”