Is it possible in R to split my date-time values into 5 different columns (Year, month, date, hour, minute)?

I am really new at R and this is probably a really basic question: Let’s say I have a dataset with a column that includes date values of the format ("y-m-d H:M:S") as a Factor value.
How do I split the one column into 5?

Given example:

x <- as.factor(c("2018-01-03 12:34:32.92382", "2018-01-03 12:50:40.00040"))

x <- as_datetime(x) #to convert to type Date
x <- x %>% 
  dplyr::mutate(year = lubridate::year(x),
                month = lubridate::month(x),
                day = lubridate::day(x),
                hour = lubridate::hour(x),
                minute = lubridate::minute(x),
                second = lubridate::second(x))

I get the error: for objects with the class(c(‘POSIXct’, ‘POSIXt’) can not be used.

>Solution :

Change it into dataframe then run mutate part will works

x %>% 
  as.data.frame() %>%
  rename(x = '.') %>%
  dplyr::mutate(year = lubridate::year(x),
                month = lubridate::month(x),
                day = lubridate::day(x),
                hour = lubridate::hour(x),
                minute = lubridate::minute(x),
                second = lubridate::second(x))

                    x year month day hour minute   second
1 2018-01-03 12:34:32 2018     1   3   12     34 32.92382
2 2018-01-03 12:50:40 2018     1   3   12     50 40.00040

Leave a Reply