0

I have a problem similar to this question R how can I calculate difference between rows in a data frame; I try to apply this solution https://stackoverflow.com/a/16212173/15485 with this code

df <- data.frame(timestamp=c("2015-02-02 09:53:44","2015-02-02 09:54:53","2015-02-02 09:55:52"),cnt=c(1,2,3))
df$timestamp <- strptime( df$timestamp, "%Y-%m-%d %H:%M:%S")
apply( df , 2 , diff )

but I get this error:

Error in r[i1] - r[-length(r):-(length(r) - lag + 1L)] : 
  non-numeric argument to binary operator

If I remove the column timestamp (which is of type POSIXlt) then it will work fine.

But... diff(df$timestamp) is working well:

Time differences in secs
[1] 69 59

So, what am I missing?

Community
  • 1
  • 1
Alessandro Jacopson
  • 18,047
  • 15
  • 98
  • 153

1 Answers1

1

You need to be careful when using apply as it converts to matrix first before doing what you define it. Since it converts your object to matrix, then it is impossible to hold dates in there. Use sapply instead, i.e.

sapply(df, diff)
Sotos
  • 51,121
  • 6
  • 32
  • 66