我遇到类似这个问题R how can I calculate difference between rows in a data frame的问题;我尝试将此解决方案https://stackoverflow.com/a/16212173/15485应用于此代码
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 )
但是我收到了这个错误:
Error in r[i1] - r[-length(r):-(length(r) - lag + 1L)] :
non-numeric argument to binary operator
如果我删除了列timestamp
(类型为POSIXlt
),那么它将正常工作。
但...... diff(df$timestamp)
运作良好:
Time differences in secs
[1] 69 59
那么,我错过了什么?
答案 0 :(得分:1)
使用apply
时需要小心,因为它在执行您定义之前首先转换为矩阵。由于它将您的对象转换为矩阵,因此无法在那里保存日期。请改用sapply
,即
sapply(df, diff)