简体   繁体   中英

R Change a column class from numeric to time

I am new to R, and am using it to do some data analysis and have reached a roadblock. I want to change the class of two of my columns ( 7 and 8 ) in my dataframe from numeric to time. At the moment they're displayed in POSIX , and I want them to be displayed as times in the format H:M I've tried:

 library(tidyverse)
 library(lubridate)
 df[7, 8] <- lapply(df[7, 8], 
                     as.POSIXct, tz = "GMT", format,
                     tryFormats = c("%H:%M"),
                     optional = TRUE)

and it comes up with the following error message:

Error in as.POSIXct.default(origin, tz = "GMT", ...): do not know how to convert 'origin' to class “POSIXct”

Any help would be much appreciated

Here is a sample from the column 7 and 8 of my dataframe

df <- structure(list(MAU_visit_time = c(42161.5416666667, 42154.8368055556, 
42160.6666666667, 42154.9583333333, NA), time_seen = c(42161.625, 
42154.9027777778, 42160.7222222222, 42154.0416666667, 42154.66875
)), class = "data.frame", row.names = c(NA, -5L))

Any help would be much appreciated

Here is what you can do. I believe the cells are seconds, so you can use

library(lubridate)
df$MAU_visit_time <- seconds_to_period(df$MAU_visit_time)
df$time_seen <- seconds_to_period(df$time_seen)

#             MAU_visit_time                 time_seen
# 1 11H 42M 41.5416666667006S           11H 42M 41.625S
# 2 11H 42M 34.8368055555984S 11H 42M 34.9027777778028S
# 3 11H 42M 40.6666666667006S 11H 42M 40.7222222221972S
# 4 11H 42M 34.9583333332994S 11H 42M 34.0416666667006S
# 5                      <NA> 11H 42M 34.6687499999971S
# -------------------------------------------------------------------------
# To extract hour(h), minute(m) and second(s)
hour(df$MAU_visit_time[1])
#11
minute(df$MAU_visit_time[1])
#42
second(df$MAU_visit_time[1])
#41.54167
hms(df$MAU_visit_time[1])
#"11H 42M 41.5416666667006S"

Update

If you want to format the column in such a way that 11:42:41.625 , you can format using it using paste , but remember, you are losing the lubridate date format (the columns will be characters).

df$MAU_visit_time <- paste(hour(df$MAU_visit_time),minute(df$MAU_visit_time),second(df$MAU_visit_time),sep=":")
df$time_seen <- paste(hour(df$time_seen), minute(df$time_seen), second(df$time_seen),sep=":")
# -------------------------------------------------------------------------

#           MAU_visit_time              time_seen
# 1 11:42:41.5416666667006           11:42:41.625
# 2 11:42:34.8368055555984 11:42:34.9027777778028
# 3 11:42:40.6666666667006 11:42:40.7222222221972
# 4 11:42:34.9583333332994 11:42:34.0416666667006
# 5               NA:NA:NA 11:42:34.6687499999971

Hope that is what you want.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM