4

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!!!

  • Can you add a sequence of code that creates df, followed by calculations on df. –  Oct 13 '14 at 14:56

1 Answers1

7

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?

Community
  • 1
  • 1
  • Thank you for your input! This is getting very close! However, I would like the right date instead of the current date. Now it gives the 12th of October instead of the 11th of August. – Sabine van Engelen Oct 13 '14 at 15:15
  • 1
    OK, concatenated the date with the end time, converted to posixct, and subtracted the box time, to create the start time; answer was updated. –  Oct 13 '14 at 15:19
  • Thank you for your input! It runs smoothly now! Thank you! – Sabine van Engelen Oct 14 '14 at 07:46