Subtracting two columns consisting of both date and time in R

I have a problem with subtracting two columns of a table consisting of date and time in one cell.

> TimeData DEPARTURE_TIME LAB_TIME 1/30/2010 4:18 1/30/2010 0:29 1/30/2010 4:18 1/30/2010 0:29 1/30/2010 6:49 1/30/2010 0:48 1/30/2010 6:49 1/30/2010 0:48 1/30/2010 9:42 1/30/2010 1:29 1/30/2010 9:42 1/30/2010 1:29 1/30/2010 7:25 1/30/2010 1:16 

I need to get the difference between departure time and lab hours in hours and minutes.

Do I need to allocate time and date, or is there a way to subtract data in this way?

I really appreciate any help.

+7
source share
1 answer

Try TimeData$DEPARTURE_TIME - TimeData$LAB_TIME ?

It depends on whether your xxx_TIME columns xxx_TIME strings or whether you converted them to date-time.

Suppose they are strings (they were read using read.csv or something similar); then, to convert them to date and time objects, you can use as.POSIXct (see ?as.POSIXct and strptime ):

 # convert the string columns to dates TimeData$DEPARTURE_TIME <- as.POSIXct(TimeData$DEPARTURE_TIME, format='%m/%d/%Y %H:%M') TimeData$LAB_TIME <- as.POSIXct(TimeData$LAB_TIME, format='%m/%d/%Y %H:%M') 

Pay attention to the argument format : looks like yours per month / day / year: format minutes (25 hours). See ?strptime more on date formats.

Then, to calculate the difference, you can do either:

 diffs <- TimeData$DEPARTURE_TIME - TimeData$LAB_TIME 

which selects the appropriate time units for you, or indicate the hours that you can use difftime (see ?difftime ):

 # like saying DEPARTURE_TIME-LAB_TIME but more control over the output diffs <- difftime(TimeData$DEPARTURE_TIME,TimeData$LAB_TIME,units="hours") 

The resulting diffs object is as follows:

 > diffs Time differences in hours [1] 3.816667 3.816667 6.016667 6.016667 8.216667 8.216667 6.150000 attr(,"tzone") [1] "" 

To extract only the numeric part, use as.numeric(diffs) . To convert this into a vector of a vector and a vector of minutes ... well, from 60 minutes to a second, etc .:

 # use as.numeric(diffs) to retrieve just the vector. # let convert to hours & minutes... diffs.hours <- floor(as.numeric(diffs)) diffs.minutes <- (as.numeric(diffs)%%1 * 60) 

Providing you:

 > diffs.hours [1] 3 3 6 6 8 8 6 > diffs.minutes [1] 49 49 1 1 13 13 9 
+12
source

All Articles