Date conversion

How can I combine these 4 date columns into one with a whole date including time?
Preferably using lubridate.

This is what the data looks like:

|Year|Month|Day|Hour|
|---|---|---|---|
|2009|1|1|0|
|2009|1|1|1|
|2009|1|1|2|
|2009|1|1|3|
|2009|1|1|4|
|2009|1|1|5|
|2009|1|1|6|
|2009|1|1|7|
|2009|1|1|8|
|2009|1|1|9|
|2009|1|1|10|

There's a quick section on exactly this in R for Data Science here:

You might have to dummy up minutes (I assume you can just use 00). I'm excerpting R4DS here, but the link will take you right to the section. You'll need to load the appropriate libraries (library(tidyverse) and library(lubridate) should cover it, I think).

Instead of a single string, sometimes you’ll have the individual components of the date-time spread across multiple columns. This is what we have in the flights data:

flights %>% 
  select(year, month, day, hour, minute)
#> # A tibble: 336,776 x 5
#>    year month   day  hour minute
#>   <int> <int> <int> <dbl>  <dbl>
#> 1  2013     1     1     5     15
#> 2  2013     1     1     5     29
#> 3  2013     1     1     5     40
#> 4  2013     1     1     5     45
#> 5  2013     1     1     6      0
#> 6  2013     1     1     5     58
#> # … with 3.368e+05 more rows

To create a date/time from this sort of input, use make_date() for dates, or make_datetime() for date-times:

flights %>% 
  select(year, month, day, hour, minute) %>% 
  mutate(departure = make_datetime(year, month, day, hour, minute))
#> # A tibble: 336,776 x 6
#>    year month   day  hour minute departure          
#>   <int> <int> <int> <dbl>  <dbl> <dttm>             
#> 1  2013     1     1     5     15 2013-01-01 05:15:00
#> 2  2013     1     1     5     29 2013-01-01 05:29:00
#> 3  2013     1     1     5     40 2013-01-01 05:40:00
#> 4  2013     1     1     5     45 2013-01-01 05:45:00
#> 5  2013     1     1     6      0 2013-01-01 06:00:00
#> 6  2013     1     1     5     58 2013-01-01 05:58:00
#> # … with 3.368e+05 more rows
1 Like

This topic was automatically closed 7 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.