R Extracting hours from time in factor format

I have a time vector that is in a factor format. For example, Time [1] is 8:01:01, the class (Time [1]) is a factor.

Now I want to extract hours and minutes from this vector. What is the most efficient way to calculate? My vector is very large. Thank you very much,

+5
source share
4 answers

One way with the lubridate package:

 Time <- factor("08:01:01") lubridate::hms(as.character(Time)) 

Edit

To extract hours and minutes:

 library(lubridate) Time <- factor("08:01:01") # parese date a <- hms(as.character(Time)) # get hours hour(a) # get minutes minute(a) 
+6
source

Try the following:

 format(strptime(Time,"%H:%M:%S"),'%H:%M') [1] "08:01" 
+6
source

You can also try a combination of converting your factor into a POSIXt object and then use the format function. I am not sure how effective this method is.

 Time <- factor("08:01:01") hour = format(as.POSIXct(Time,format="%H:%M:%S"),"%H") minute = format(as.POSIXct(Time,format="%H:%M:%S"),"%M") paste(hour,minute,sep=":") [1] "08:01" 
+3
source

How about this

  Time <- factor("08:01:01") Time2 <- strptime(Time, "%H:%M:%S") Time3 <- format(Time2, "%H:%M") 

time3

[1] 08:01

+1
source

Source: https://habr.com/ru/post/1236744/


All Articles