代码之家  ›  专栏  ›  技术社区  ›  LulY

是否存在difftime()版本矢量?

  •  0
  • LulY  · 技术社区  · 3 年前

    我有日期时间矢量,它们的条目非常不同。有时条目之间的间隔只有几秒,有时是几天。就像这样:

    # Vector increasing by seconds
    time1 <- ymd_hms(c("2023-05-02 14:15:00", "2023-05-02 14:15:01", "2023-05-02 14:15:02"))
    # Vector increasing by days
    time2 <- ymd_hms(c("2023-05-02 14:15:00", "2023-05-03 14:15:00", "2023-05-04 14:15:00"))
    

    我需要知道所有矢量的时间差。的问题 diff() 它会自动选择一个时间单位,而我们不能设置自己的单位(否 unit 自变量):

    diff(time1) == diff(time2)
    # TRUE
    

    幸运的是 difftime() 函数具有 单元 论点但是 difftime 它不接受矢量:

    difftime(time1)
    # Error in difftime(time1) : argument "time2" is missing, with no default
    

    有没有一个函数可以计算整个向量的差,我们可以设置单位?我想有比 sapply(seq(1, length(time1)-1, 1), function(i){difftime(time1[i+1], time1[i], units= "sec")}) ?

    0 回复  |  直到 3 年前
        1
  •  1
  •   jpsmith    3 年前

    在基R中 as.numeric 函数接受 units = 可以与一起使用的论点 diff() 其在输出中提供灵活性:

    # time 1, in seconds
    as.numeric(diff(time1), units = "secs")
    # [1] 1 1
    as.numeric(diff(time1), units = "days")
    # [1] 1.157407e-05 1.157407e-05
    
    # time 2, in days
    as.numeric(diff(time2), units = "days")
    # [1] 1 1
    as.numeric(diff(time2), units = "secs")
    # [1] 86400 86400
    
        2
  •  0
  •   NicChr    3 年前

    如果你想要更大的灵活性,你可以使用我的功能 time_diff() 使用 lubridate 以支持周期时间差异以及通常的持续时间差异。

    # remotes::install_github("NicChr/timeplyr")
    library(timeplyr)
    library(dplyr)
    library(lubridate)
    
    tdiff <- function(x, n = 1, ...){
      out <- time_diff(dplyr::lag(x, n = n), x, ...)
      tail(out, n = -n)
    }
    
    tdiff(time1, by = "sec", n = 1)
    #> [1] 1 1
    # Period or duration differences
    tdiff(time1, by = "month", type = "period")
    #> [1] 3.733572e-07 3.733572e-07
    tdiff(time1, by = "month", type = "duration")
    #> [1] 3.802571e-07 3.802571e-07
    

    创建于2023-05-04 reprex v2.0.2

        3
  •  -1
  •   Eduards    3 年前

    是的,您可以将difftime()函数与向量一起使用,方法是将time1和time2参数指定为相同长度的向量。要计算特定单位的时差,可以将单位参数设置为所需的单位。