Home > Net >  How to change the class of time column from character to POSIXct
How to change the class of time column from character to POSIXct

Time:06-08

How do I change the class of sleep_time and wake_time columns from character to POSIXct?(Dataset clip is attached below)

I tried this but it didn't work

data$sleep_time <- as.Date(data$sleep_time, format = "%h.%m.%s")

Dataset clip

CodePudding user response:

First provide reproducible data using dput():

data <- structure(list(date = "16-03-2022", sleep_time = "01.01", wake_time = "06.02"), class = "data.frame", row.names = c(NA, 
-1L))
as.POSIXct(paste(data$date, data$sleep_time), format = "%d-%m-%Y %H.%M")
# [1] "2022-03-16 01:01:00 CDT"
as.POSIXct(paste(data$date, data$wake_time), format = "%d-%m-%Y %H.%M")
# [1] "2022-03-16 06:02:00 CDT"

See ?as.POSIXct for details.

CodePudding user response:

As mentioned in the comments, if you want to convert to POSIXct, then you need to combine the time with the date. Here, we can paste the date and time together, then convert to as.POSIXct.

library(tidyverse)

df %>%
  mutate(sleep_time = as.POSIXct(paste(date, sleep_time), format="%d-%m-%Y %H.%M"),
         wake_time = as.POSIXct(paste(date, wake_time), format="%d-%m-%Y %H.%M"))

Output

        date          sleep_time           wake_time
1 16-03-2022 2022-03-16 01:01:00 2022-03-16 06:02:00
2 16-03-2022 2022-03-16 23:07:00 2022-03-16 06:25:00
3 16-03-2022 2022-03-16 01:48:00 2022-03-16 08:23:00

If you are just wanting to get it into that time format, then you can convert the only keep the time, although it would just be character then.

df %>%
  mutate(sleep_time = format(strptime(sleep_time,format="%H.%M"), format="%H:%M:%S"),
         wake_time = format(strptime(wake_time, format="%H.%M"), format="%H:%M:%S"))

#        date sleep_time wake_time
#1 16-03-2022   01:01:00  06:02:00
#2 16-03-2022   23:07:00  06:25:00
#3 16-03-2022   01:48:00  08:23:00

Data

df <- structure(list(date = c("16-03-2022", "16-03-2022", "16-03-2022"
), sleep_time = c(1.01, 23.07, 1.48), wake_time = c(6.02, 6.25, 
8.23)), class = "data.frame", row.names = c(NA, -3L))
  •  Tags:  
  • r
  • Related