calculating time difference in R
You must turn your strings into date objects before you can do date/time arithmetic. Try this:
a) Reading your data:
R> dat <- read.table(textConnection("start.date start.time end.date end.time
2012-07-13 15:01:32 2012-07-13 15:02:42
2012-07-05 18:26:31 2012-07-05 18:27:19
2012-07-14 20:23:21 2012-07-14 20:24:11"), header=TRUE)
b) Working on one observation:
R> strptime( paste(dat[,1], dat[,2]), "%Y-%m-%d %H:%M:%S")
[1] "2012-07-13 15:01:32" "2012-07-05 18:26:31" "2012-07-14 20:23:21"
c) Working on the set, converting to numeric:
R> as.numeric(difftime(strptime(paste(dat[,1],dat[,2]),"%Y-%m-%d %H:%M:%S"),
strptime(paste(dat[,3],dat[,4]),"%Y-%m-%d %H:%M:%S")))
[1] -70 -48 -50
R>
Edit Some seven years later by someone else below.
d) Just to explain the results -70 -48 -50
above take a look at the example row by row:
[2012-07-13 15:01:32] - [2012-07-13 15:02:42] = -70 seconds,
[2012-07-05 18:26:31] - [2012-07-05 18:27:19] = -48 seconds,
[2012-07-14 20:23:21] - [2012-07-14 20:24:11] = -50 seconds
I think you can use the lubridate package
it has a method called ymd_hms
you can use that to get the time from string:
it is much faster for large data set
library(lubridate)
dat <- read.table(textConnection("start.date start.time end.date end.time
2012-07-13 15:01:32 2012-07-13 15:02:42
2012-07-05 18:26:31 2012-07-05 18:27:19
2012-07-14 20:23:21 2012-07-14 20:24:11"), header=TRUE)
starttime = ymd_hms(paste(dat[,1], dat[,2]))
endtime = ymd_hms(paste(dat[,3], dat[,4]))
interval = difftime(endtime,starttime,units = "secs")
or you can just do it in one line, but it takes longer time for big dataset:
difftime(paste(dat[,3], dat[,4]),paste(dat[,1], dat[,2]),units = "secs")