How can I make my dates maintain their type in after a `purrr::cross_df()`?

purrr

#1

How can I make my dates maintain their type in after a purrr::cross_df()?

It seems that my date type changes after a cross_df() how can I prevent this or change it back?

library(tidyverse)
library(lubridate)
#> 
#> Attaching package: 'lubridate'
#> The following object is masked from 'package:base':
#> 
#>     date
# make sequence of 24 hours
hrs <- seq(1,24,1)

# make sequence of dates given date range
date <- seq.Date(as.Date("2018-08-02"), as.Date("2018-11-26"), "1 day")

# cross hours with dates
hrs_dates <- list(hrs = hrs, date = date)
str(hrs_dates)
#> List of 2
#>  $ hrs : num [1:24] 1 2 3 4 5 6 7 8 9 10 ...
#>  $ date: Date[1:117], format: "2018-08-02" "2018-08-03" ...
hrs_dates %>% cross_df() %>% str
#> Classes 'tbl_df', 'tbl' and 'data.frame':    2808 obs. of  2 variables:
#>  $ hrs : num  1 2 3 4 5 6 7 8 9 10 ...
#>  $ date: num  17745 17745 17745 17745 17745 ...

Created on 2018-11-28 by the reprex package (v0.2.1)


#2

This behavior comes from transpose -- https://github.com/tidyverse/purrr/issues/471 -- and it might be fixed at some point - https://github.com/tidyverse/purrr/pull/554.

If you don't want to wait then you'll probably can get around with two conversions date -> string -> date like this:

library(magrittr)
hrs <- seq(1,24,1)
date <- seq(as.Date("2018-08-02"), as.Date("2018-11-26"), "1 day") %>%
  as.character()

# cross hours with dates
hrs_dates <- list(hrs = hrs, date = date)
hrs_dates %>% 
  purrr::cross_df() %>%
  dplyr::mutate(date = as.Date(date))
#> # A tibble: 2,808 x 2
#>      hrs date      
#>    <dbl> <date>    
#>  1     1 2018-08-02
#>  2     2 2018-08-02
#>  3     3 2018-08-02
#>  4     4 2018-08-02
#>  5     5 2018-08-02
#>  6     6 2018-08-02
#>  7     7 2018-08-02
#>  8     8 2018-08-02
#>  9     9 2018-08-02
#> 10    10 2018-08-02
#> # ... with 2,798 more rows

Created on 2018-11-28 by the reprex package (v0.2.1)


#3

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