我想知道如何计算R中的时差。 我想要做的是写一个for循环,在一个序列中将两次差异相加。我的时间价值是:
class(time_tracker[["Time"]])
[1] "POSIXct" "POSIXt"
我这里有这个代码会抛出一个错误:如果是正数,则列索引必须至多为1,而不是2。
time_diff <- vector(length = nrow(time_tracker) / 2)
for (ii in 1:nrow(time_tracker)) {
if (ii %% 2 == 1) {
time_diff[ii] <- 0
next
}
time_diff[ii] <- time_tracker[ii] - time_tracker[ii-1]
}
编辑:我附加了dput(time_tracker)的结果
> dput(time_tracker)
structure(list(Time = structure(c(1514816115.47, 1514830259.635,
1514902914.733, 1514914080.377, 1514985907.22, 1514991852.622,
1515074871.862, 1515083693.884, 1515157263.375, 1515164762.199,
1515171659.051, 1515178817.472, 1515412548.314, 1515421898.408,
1515426894.401, 1515432378.804, 1515510162.063, 1515521213.24,
1515587687.496, 1515592079.084, 1515596566.348, 1515601214.072,
1515669624.922, 1515674005.052, 1515678130.703, 1515683168.14,
1515693012.189, 1515702965.051, 1515766180.92, 1515777198.981,
1516120746.324, 1516123811.672, 1516378829.789, 1516383306.033,
1516454060.532, 1516460219.87, 1516628714.27, 1516631433.181,
1516836119.135, 1516840996.022, 1516979800.66, 1516982200.996,
1517071285.444, 1517074935.673), class = c("POSIXct", "POSIXt"
), tzone = "UTC")), class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA,
-44L), .Names = "Time")
答案 0 :(得分:0)
在修改拼写错误以便选择列之后,上面的代码会创建一个类似c(time2 - time1, 0, time4 - time3, 0, time6 - time5, ...)
等的向量。这是您要找的吗?
如果您要查找每个连续时间之间的时差,则更容易使用diff(time_tracker[ ,1], lag = 1)