Hour and minutes in one column in R
I have a simple frame. From which I want to add another column that records the time (hours and minutes, in a 24 hour clock). Then I'm going to display this column against a variable. Since the dates are still the same, I'm only interested in the time. This is what I have tried so far.
a <- c(1:6)
b <- c("05/12/2012 05:00","05/12/2012 06:55","05/12/2012 07:10",
"05/12/2012 10:23", "05/12/2012 11:43","05/12/2012 13:04")
c <-c("0","0","0","1","1","1")
df1 <- data.frame(a,b,c,stringsAsFactors = FALSE)
a <- df1$a
b <- strptime(df1$b, "%d/%m/%Y %H:%M")
c <- as.numeric(df1$c)
hour <- as.numeric(format(b, "%H"))
min <- as.numeric(format(b, "%M"))
date <- format(b, "%x")
time <- hour + min
df2 <- data.frame(a, b, c, hour, min, date, time)
I was advised here to convert minutes and hours manually by splitting the numbers separately, converting them to similar units, and then adding. However I am scared as 5 AM is just imported as 5.
If anyone could advise me on how I could do this properly, I would really appreciate it.
source to share
There are many conversion tools for dates and times, and a whole bunch of packages to use. I like working with POSIXlt
in this case, as you can extract all the information you need by simply pulling them out of the list.
eg:
a <- c(1:6)
b <- c("05/12/2012 05:00","05/12/2012 06:55","05/12/2012 07:10",
"05/12/2012 10:23", "05/12/2012 11:43","05/12/2012 13:04")
c <-c("0","0","0","1","1","1")
df1 <- data.frame(a,b,c,stringsAsFactors = FALSE)
df2 <- within(df1,{
posb <- as.POSIXlt(b,format="%d/%m/%Y %H:%M")
hours <- posb$hour
mins <- posb$min
dates <- format(posb, "%x")
time <- format(posb, "%H:%M")
posb <- NULL # cleanup
})
What gives:
> df2
a b c time dates mins hours
1 1 05/12/2012 05:00 0 05:00 12/5/2012 0 5
2 2 05/12/2012 06:55 0 06:55 12/5/2012 55 6
3 3 05/12/2012 07:10 0 07:10 12/5/2012 10 7
4 4 05/12/2012 10:23 1 10:23 12/5/2012 23 10
5 5 05/12/2012 11:43 1 11:43 12/5/2012 43 11
6 6 05/12/2012 13:04 1 13:04 12/5/2012 4 13
For more information see also:
-
?POSIXlt
for more information on POSIXt classes -
?format
for more information on formatting options -
?strptime
for more information on formatting options and conversion to character -
lubridate
package for alternative functions -
timeDate
package for a few more alternative functions - ...
source to share