How to find the difference between two rows of data consisting of date and time in R -
i working data file consisting of 1 column of date , time
df time_stamp 1 2003-09-06t20:21:51z (2003-09-06--> year-month-days-hours-mintutes-seconds) 2 2003-09-06t20:22:36z 3 2003-09-06t20:22:51z 4 2003-09-06t20:23:06z 5 2003-09-06t20:24:56z 6 2003-09-06t20:25:06z
i want find difference between 2 rows based on unit of minutes. have applied code 1st convert data date format, gives me error like:
x<-as.date(df,format='%d/%b/%y:%h:%m:%s') error in as.date.default(datew, format = "%d/%b/%y:%h:%m:%s") : not know how convert 'datew' class “date”
while mode(df) shows results of "list"
any highly appreciated. output should as:
df time_stamp time_duration 1 2003-09-06t20:21:51z 0 2 2003-09-06t20:22:36z 1 3 2003-09-06t20:22:51z 0.25 4 2003-09-06t20:23:06z 0.25 5 2003-09-06t20:24:56z 1.8 6 2003-09-06t20:25:06z 0.17
thanks, in advance.
you seem passing list as.date
function, , doesn't know how deal lists. try following.
first create data
time_stamp <- c( "2003-09-06t20:21:51z", "2003-09-06t20:22:36z", "2003-09-06t20:22:51z", "2003-09-06t20:23:06z", "2003-09-06t20:24:56z", "2003-09-06t20:25:06z") df <- list(time_stamp=time_stamp)
now turn posix date. note format="%y-%m-%dt%h:%m:%sz"
argument differs yours, since yours produced error when tried it. format
has reflect nature of date string. see help(strptime)
details.
x<-as.posixct(df$time_stamp,format="%y-%m-%dt%h:%m:%sz" , tz="gmt") # comparison @akrun suggested time_duration <- difftime(x[-1], x[-length(x)], unit='mins') # add 0 start time_duration <- c(0 , time_duration) # make dataframe df <- data.frame( time_stamp=df$time_stamp , time_duration=time_duration )
and result wanted:
> df time_stamp time_duration 1 2003-09-06t20:21:51z 0.0000000 2 2003-09-06t20:22:36z 0.7500000 3 2003-09-06t20:22:51z 0.2500000 4 2003-09-06t20:23:06z 0.2500000 5 2003-09-06t20:24:56z 1.8333333 6 2003-09-06t20:25:06z 0.1666667
Comments
Post a Comment