【问题标题】:R lead and lag (shift) with timesR 随时间领先和滞后(移位)
【发布时间】:2017-07-04 10:27:40
【问题描述】:

我尝试在数据框的一列上使用延迟,但是当涉及到时间时,它就不起作用了。我试过 shift、lag 和 tlag。

例子:

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))

格式错误。POSIXlt(x, usetz = usetz): "POSIXlt" 中的无效组件 [[10]] 应为 'zone'

tlag(c(y,yy))

n_distinct_multi(list(...), 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

我不想要任何时间差异,我只想要数据框中上面行的值,我认为这是 lag 所做的:“领先和滞后对于比较由常数偏移的值很有用(例如上一个或下一个值)”。 时间甚至都不重要,它应该从前一个位置选择任何数字/字符/时间。我该如何解决这个问题,或者是否有一个不同的功能可以完成我想要的功能 - 我不想涉及任何循环,因为速度很重要并且数据帧很大。

来自我的数据框的示例:

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"))

【问题讨论】:

  • 最好发布一个包含您在文本中提到的数据框的可重现示例。我的怀疑是,你想要做的是非常直接的,使用 mutate 和 lag 的 tidyverse 方法,但目前很难看到。
  • 预期输出是什么?
  • 那么数据框的行为与上面的向量相同,它显示错误而不是预期的 'NA, "2017-07-04 04:20:10 BST"'
  • 在使用data.frames 时,始终将您的时间变量转换为POSIXctdata.frame 不能很好地处理POSIXlt,因为它是一个内部列表。 strptime 确实返回 POSIXlt
  • 谢谢,成功了。为什么/如何在无需进行任何类转换的情况下使用以下答案?

标签: r time lag shift lead


【解决方案1】:

对于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          

【讨论】:

  • 为什么使用 POSIXlt 可以在 mutate 中工作,但没有 mutate 我必须转换为 POSIXct?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-01-25
  • 2021-06-04
  • 2018-01-03
  • 1970-01-01
  • 2018-07-01
  • 2018-09-01
  • 1970-01-01
相关资源
最近更新 更多