Subtracting time in r
I have a dataset containing two variables for time: EndVisitTime
and BoxTime
. I was doing data per day (so these observations are all in one day):
Date<-"2014-8-12"
EndVisitTime<-c("00:00:32", "00:04:52", "00:10:01", "00:23:38", "00:31:28") # class: factor
BoxTime<-as.integer(c("341", "229", "301", "810", "363")) # class integer in seconds
df<-data.frame(Date, EndVisitTime, BoxTime)
I want to calculate StartVisitTime
; that is EndVisitTime - BoxTime
.
When the visit started on the previous day, I want to get the correct start date ( date = 2014-8-11
). My question is how to subtract BoxTime
(which is in seconds) from EndVisitTime
to get the correct one StartVisitTime
with the correct one StartDate
??
I tried several options and I can't get any more as they keep adding the current date or the result in 0 to 1 traits which cannot be converted to date and time format.
# This is my most successful attempt
df$EndTime<-strptime(df$EndVisitTime, format="%H:%M:%S")
df$BoxTime<-as.numeric(df$BoxTime)
library("chron")
df$x<-chron(times=(df$BoxTime/(60*60*24)))
df$StartVisitTime<-df$EndTime-df$x ### This does not work!
Your help is greatly appreciated and willing !!!
source to share
Using POSIXct dates, seconds can be added directly.
Sample data
df<-data.frame(EndVisitTime=c("00:00:32", "00:04:52", "00:10:01", "00:23:38", "00:31:28"),
BoxTime=c("341", "229", "301", "810", "363"),
Date = "2014-8-12",stringAsFactor=FALSE)
Combine date and time into one line
df$EndTimeStr<-do.call(paste, df[,c("Date", "EndVisitTime")])
Convert to POSIXct time
df$EndTime<-as.POSIXct(df$EndTimeStr,format="%Y-%m-%d %H:%M:%S")
Subtract seconds
df$BoxTime<-as.numeric(df$BoxTime)
df$StartVisitTime<-df$EndTime-df$BoxTime
df
Ref How to add / subtract time from POSIXlt while keeping its class in R?
source to share