How do I get the time difference with minutes and seconds?
I have two columns of time information using minutes and seconds in data.frame without any 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 both seconds ( diff_time1 ) or in minutes and seconds as stated 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
source to share
Assuming your time is stored as strings, in this case, the quote denoting the seconds should 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 calculations. You will need to do some additional text transformations if you want the results to be 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
source to share
You can store individual minutes and seconds and store them as objects difftime
that 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
source to share