Converting hour, minutes columns in dataframe to time format
-
30-05-2021 - |
Question
I have a dataframe containing 3 columns including minutes and hours.
I want to convert these columns (namely minutes and column) to time format. Given the data in drame
:
Score Hour Min
10 10 56
23 17 01
I would like to get:
Score Time
10 10:56:00
23 17:01:00
Solution
You could use ISOdatetime
to convert the numbers in the hour
and min
to a POSIXct
object. However, a POSIXct object is only defined when it also includes a year, month and day. So depending on your needs to can do several things:
- If you need a real time object which is correctly printed in graphs for example and can be used in arithmetic (addition, subtraction), you need to use
ISOdatetime
.ISOdatetime
returns a so calledPOSIXct
object, which is an R object which represents time. Then inISOdatetime
you just use fixed values foryear
,month
, andday
. This ofcourse only works if your dataset does not span multiple years. - If you just need a character column
Time
, you can convert thePOSIXct
output to string usingstrftime
. By setting theformat
argument to"%H:%M:00"
. In this case however, you could also usesprintf
to create the new character column without converting toPOSIXct
:sprintf("%s:%s:00", drame$Hour, drame$Min)
.
OTHER TIPS
You can use paste() function to merge the two column data into a char and then use strptime() to convert to timestamp
x<-1:6
##1 2 3 4 5 6
y<-8:13
## 8 9 10 11 12 13
timestamp <- paste(x,":",y,":00",sep="")
timestamp
will result in
#1:8:00 2:9:00 3:10:00 4:11:00 5:12:00 6:13:00
If you prefer to convert this to timestamp object try using
strptime(mergedData,"%H:%M:%S")
## uses current date by default
if you happen to have Date in another column use paste() to make a char formattted date and use below to get date time
##strptime(mergedData,"%d/%m/%Y %H:%M:%S")