Home > other >  Is it possible in R to split my date-time values into 5 different columns (Year, month, date, hour,
Is it possible in R to split my date-time values into 5 different columns (Year, month, date, hour,

Time:06-16

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.

CodePudding user response:

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

CodePudding user response:

You could also make your mutate a little bit cleaner utilizing the power of across:

library(lubridate)

x %>%
  data.frame(date = .) %>%
  mutate(across(date,
                funs(year, month, day, hour, minute, second),
                .names = "{.fn}"))
  • Related