Reputation: 105
I have a dataframe with a time period column that is saved as characters and is in the following format:
x
[1] "00:17:31.199" "1 day 01:37:46.22" "00:43:11.51" "01:18:37.721" ...
I would like to convert the values of this column to hours (and hour decimals) 31/ so that the returning column is
[1] 0.28 25.61 0.71 1.3 ...
in which 0.28 is 17/60 hours and 25.61 is equal to 24+1+37/60. Note that everything is saved as characters. I couldn't find any command in baseR or lubridate to figure this out. Any help?
Upvotes: 0
Views: 760
Reputation: 105
So, I ended up doing the following based on @Mako212 and @thelatemail:
days <- gsub("(\\d+)(?=\\sday).*", "\\1", x, perl=TRUE) # extracting the number of days
hours <- gsub(".*(\\S*\\s+\\S+)", "\\1", x, perl=TRUE) # getting rid of days
ind <- grep("(\\d+)(?=\\sday).*", x, perl=TRUE) # getting the indices of elements that have days
Then I used as.difftime
in order to calculate the time difference in hours.
time.hours <- as.difftime(x, format="%H:%M:%OS", units="hours")
Now, I need to calculate the days that I extracted in vector days
in terms of hours and add it to time.hours
.
for (i in ind) {
time.hours[ind] <- as.numeric(days[ind])*24 +
as.difftime(hours[ind], format="%H:%M:%OS", units="hours")
}
Note that there might be a more efficient way of doing the above loop but that's how I did it.
Upvotes: 1