Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R Extract Hours from Time in factor Format

Tags:

r

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,

like image 530
NewbieDave Avatar asked Nov 24 '15 21:11

NewbieDave


People also ask

How do I read a timestamp in R?

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.

Does R have a time data type?

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.


2 Answers

Try this:

format(strptime(Time,"%H:%M:%S"),'%H:%M') [1] "08:01" 
like image 86
Shenglin Chen Avatar answered Nov 10 '22 09:11

Shenglin Chen


One way with the lubridate package would be:

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)
like image 37
johannes Avatar answered Nov 10 '22 09:11

johannes