Reputation: 339
I have a variable in the form of minutes spent in an activity. I would like to convert this number into hours and minutes by taking the digits into account but without producing seconds. Here's an example:
minutes<-c(81.4398, 50.9903,107.5511,433.3051,10.1234)
minutes
I would like the outcome in a clock format:
hrsmins<- c(1:21,0:51,1:48,7:13,0:10)
Note that the outcome, does not show the clock time of the day but hours and minutes in the activity. I have a very large data set (millions of episodes). So, I would appreciate if someone can offer an efficient way of doing this conversion.
Upvotes: 7
Views: 10257
Reputation: 3883
Really, the question appears to want to round (rather than truncate?) the data to the closest minute and display as hours and minutes.
There are lots of packages that allow you to save data as a time variable and round it to the nearest minute (chron
, data.table
, lubridate
, hms
), but they don't provide good documentation on how to format the result and drop the seconds. I've resorted to a work-around below.
minutes<-c(81.4398, 50.9903,107.5511,433.3051,10.1234, 119.99)
## With Chron but formatting isn't working correctly?
format(chron::as.times(round(minutes)/60/24), "h:m")
#> [1] "0121" "0051" "0148" "0713" "0010" "0200"
substr(as.character(chron::as.times(round(minutes)/60/24)), 1, 5)
#> [1] "01:21" "00:51" "01:48" "07:13" "00:10" "02:00"
## With data.table
substr(as.character(round(data.table::as.ITime(minutes*60), "minutes")), 1, 5)
#> [1] "01:21" "00:51" "01:48" "07:13" "00:10" "02:00"
## With hms
substr(as.character(hms::round_hms(hms::hms(minutes = minutes), secs = 60)), 1,5)
#> [1] "01:21" "00:51" "01:48" "07:13" "00:10" "02:00"
## Doesn't work as I'd expect?
format(hms::round_hms(hms::hms(minutes = minutes), secs = 60), "%H:%M")
#> [1] "01:21:00" "00:51:00" "01:48:00" "07:13:00" "00:10:00" "02:00:00"
Created on 2023-03-03 with reprex v2.0.2
Upvotes: 0
Reputation: 887048
We can try with chron
library(chron)
substr(times((minutes%/%60 + minutes%%60 /60)/24), 1, 5)
#[1] "01:21" "00:50" "01:47" "07:13" "00:10"
Or it could be
sub(":\\d{2}", "", times((minutes%/%60 + minutes%%60 /3600)/24))
#[1] "01:21" "00:51" "01:48" "07:13" "00:10"
Upvotes: 8