I have a vector of time that is in the format of factor. For instance, Time[1] is 8:01:01, class(Time[1]) is factor.
Now I want to extract hours and minute from this vector. What is the most computational efficient way of doing it? My vector is very large. Thank you so much,
Method 1: Using POSIXct class in R POSIXct method can be used which converts a date-time string variable into a POSIXct class. as. POSIXct method is used which stores both the date and time along with an associated time zone in R.
R has developed a special representation for dates and times. Dates are represented by the Date class and times are represented by the POSIXct or the POSIXlt class. Dates are stored internally as the number of days since 1970-01-01 while times are stored internally as the number of seconds since 1970-01-01.
Try this:
format(strptime(Time,"%H:%M:%S"),'%H:%M') [1] "08:01"
One way with the lubridate
package would be:
Time <- factor("08:01:01")
lubridate::hms(as.character(Time))
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With