R先导和滞后(移位)与时间
问题描述:
我试图在数据框的列上使用滞后,但是当涉及时间它不会工作。我尝试过移位,滞后和tlag。R先导和滞后(移位)与时间
实施例:
y = strptime(sprintf("%s:%s:%s", 4, 20, 10), "%H:%M:%S")
yy = strptime(sprintf("%s:%s:%s", 10, 20, 10), "%H:%M:%S")
lag(c(y,yy))
错误format.POSIXlt(X,usetz = usetz): 无效成分[[10]]在 “POSIXlt” 应为 '区域'
tlag(c(y,yy))
错误n_distinct_multi(列表(...),na.rm): 参数“时间”缺失,没有默认设置
shift(c(y,yy))
[[1]]
[1] NA 10
[[2]]
[1] NA 20
[[3]]
[1] NA 4
[[4]]
[1] NA 4
[[5]]
[1] NA 6
[[6]]
[1] NA 117
[[7]]
[1] NA 2
[[8]]
[1] NA 184
[[9]]
[1] NA 1
[[10]]
[1] NA "BST"
[[11]]
[1] NA 3600
我不希望任何时间差,我只是想在上面我的数据帧,我认为从该行的值是什么做的滞后:“先导和滞后对比较由常数偏移的值有用(例如,上一个或下一个值)“。 时间应该不重要,它应该从上一个位置选择任何数字/字符/时间。我该如何解决这个问题,或者是否有一个不同的功能,它相当于我倒是喜欢 - 我不想涉及任何环路作为速度是很重要的数据帧都很大
实例从我的数据帧。
structure(list(sec = c(52, 53, 54, 55, 56, 57, 58, 59, 0, 1),
min = c(50L, 50L, 50L, 50L, 50L, 50L, 50L, 50L, 51L, 51L),
hour = c(11L, 11L, 11L, 11L, 11L, 11L, 11L, 11L, 11L, 11L
), mday = c(4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L), mon = c(6L,
6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L), year = c(117L, 117L,
117L, 117L, 117L, 117L, 117L, 117L, 117L, 117L), wday = c(2L,
2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L), yday = c(184L, 184L,
184L, 184L, 184L, 184L, 184L, 184L, 184L, 184L), isdst = c(1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), zone = c("BST", "BST",
"BST", "BST", "BST", "BST", "BST", "BST", "BST", "BST"),
gmtoff = c(NA_integer_, NA_integer_, NA_integer_, NA_integer_,
NA_integer_, NA_integer_, NA_integer_, NA_integer_, NA_integer_,
NA_integer_)), .Names = c("sec", "min", "hour", "mday", "mon",
"year", "wday", "yday", "isdst", "zone", "gmtoff"), class = c("POSIXlt",
"POSIXt"))
答
对于data.frame
像下面
index time
1 1 2017-07-04 04:20:10
2 2 2017-07-04 10:20:10
您可以使用dplyr
dplyr::lag(df$time, 1)
[1] NA "2017-07-04 04:20:10 CEST"
dplyr::lead(df$time, 1)
[1] "2017-07-04 10:20:10 CEST" NA
而到了超前/滞后列添加到您的data.frame
可以使用
dplyr::mutate(df, lead_1 = dplyr::lead(time, 1), lag_1 = dplyr::lag(time, 1))
index time lead_1 lag_1
1 1 2017-07-04 04:20:10 2017-07-04 10:20:10 <NA>
2 2 2017-07-04 10:20:10 <NA> 2017-07-04 04:20:10
+0
为什么使用POSIXlt在mutate中工作,但没有mutate我必须转换为POSIXct? – Olivia
这将是更好张贴包含在文本提到的数据帧重复的例子。我的怀疑是,你想要做的事情很简单,使用变异和滞后的方法来完成,但目前很难看清楚。 – JanLauGe
什么是预期产出? – AK88
那么数据框会和上面的矢量一样,它会显示错误而不是预期的'NA',2017-07-04 04:20:10 BST“' – Olivia