Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading