问题
I have a dataset that contains two variables for time: EndVisitTime and BoxTime. I have made data sets per day (so these observations are all on 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 the previous day I want to get the right start date (date = 2014-8-11).
My question is how can I subtract BoxTime (which is in seconds) from EndVisitTime to get the right StartVisitTime with the right StartDate??
I have tried several options and I cannot get any further as they keep adding the current date or result in a 0 to 1 trait that cannot be transformed to time-date 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 very much appreciated and wanted!!!
回答1:
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 the date and time into a single string
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 the seconds
df$BoxTime<-as.numeric(df$BoxTime)
df$StartVisitTime<-df$EndTime-df$BoxTime
df
Ref How to add/subtract time from a POSIXlt time while keeping its class in R?
来源:https://stackoverflow.com/questions/26342473/subtract-time-in-r