Reputation: 527
I have two columns of time information using minutes and seconds in a data.frame without additional date information, now I want to calculate the difference between these two columns and get a new column for diff_time (end_time-start_time) in either seconds (diff_time1) or in minutes and seconds as expressed in the original variables(diff_time2), how can I calculate this in R? For example:
start_time end_time diff_time1 diff_time2
12'10" 16'23" 4'13" 253
1'05" 76'20" 75'15" 4515
96'10" 120'22" 24'12" 1452
Upvotes: 4
Views: 1721
Reputation: 43334
You can store separate the minutes and seconds and store them as difftime
objects, which can be added and subtracted:
library(tidyverse)
df <- structure(list(start_time = c("12'10\"", "1'05\"", "96'10\""),
end_time = c("16'23\"", "76'20\"", "120'22\"")), class = "data.frame", row.names = c(NA,
-3L), .Names = c("start_time", "end_time"))
df %>%
separate(start_time, c('start_min', 'start_sec'), convert = TRUE, extra = 'drop') %>%
separate(end_time, c('end_min', 'end_sec'), convert = TRUE, extra = 'drop') %>%
mutate(start = as.difftime(start_min, units = 'mins') + as.difftime(start_sec, units = 'secs'),
end = as.difftime(end_min, units = 'mins') + as.difftime(end_sec, units = 'secs'),
diff_time = end - start)
#> start_min start_sec end_min end_sec start end diff_time
#> 1 12 10 16 23 730 secs 983 secs 253 secs
#> 2 1 5 76 20 65 secs 4580 secs 4515 secs
#> 3 96 10 120 22 5770 secs 7222 secs 1452 secs
Upvotes: 0
Reputation: 33772
Assuming that your times are stored as strings, in which case the quote denoting seconds must be escaped:
times <- data.frame(start_time = c("12'10\"", "1'05\"", "96'10\""),
end_time = c("16'23\"", "76'20\"", "120'22\"")
)
Then you can use lubridate::ms
to convert to minutes + seconds and do the calculations. You'll need to do some additional text conversions if you want the results for diff_time1
as strings:
library(lubridate)
library(dplyr)
times %>%
mutate(diff_time1 = ms(end_time) - ms(start_time)) %>%
mutate(diff_time2 = as.numeric(diff_time1)) %>%
mutate(diff_time1 = gsub("M ", "'", diff_time1)) %>%
mutate(diff_time1 = gsub("S", "\"", diff_time1))
start_time end_time diff_time1 diff_time2
1 12'10" 16'23" 4'13" 253
2 1'05" 76'20" 75'15" 4515
3 96'10" 120'22" 24'12" 1452
Upvotes: 7