【问题标题】:Filtering by a specific number of days using lubridate使用 lubridate 按特定天数过滤
【发布时间】:2021-09-11 03:31:21
【问题描述】:

我有一个数据集,我想以 10 天为间隔进行分隔。例如,我想将 ID 1 的所有日期 26-12-201004-01-2011 放在一起,而不是将 ID 1 的下一个 10 天放在一起。我想为每个ID 执行此操作,并将 10 天的时间间隔编译成一个列表。

library(lubridate)
date <- rep_len(seq(dmy("26-12-2010"), dmy("20-12-2013"), by = "days"), 500)
ID <- rep(seq(1, 5), 100)

df <- data.frame(date = date,
                 x = runif(length(date), min = 60000, max = 80000),
                 y = runif(length(date), min = 800000, max = 900000),
                 ID)

df %>% 
    mutate(interval = map(1:50, ~rep(.x, 10)) %>% reduce(c)) %>% 
    group_split(interval) %>%
    map(~arrange(.x, ID)) %>% 
    map(~ group_split(.x, ID)) %>% 
    head(2)
)

使用最后几行代码时,它会破坏 daysIDs,但假设在 10 天内的观察结果并未组合在一起。

【问题讨论】:

  • 当我尝试代码时,您的 date 对象不是 Date 类。
  • df %&gt;% group_by(day10 = cut(date, "10 days")) 这样的东西怎么样?

标签: r dplyr tidyverse lubridate


【解决方案1】:

昨天我很难理解你想要的输出,但我不知道你为什么不首先安排所有IDs。我希望这是您正在寻找的:

library(dplyr)
library(magrittr)

# slicing first 2 elements only
df %>%
  arrange(ID) %>% 
  mutate(cut = data.table::rleid(cut(date, breaks = "10 day"))) %>% 
  group_split(ID, cut) %>%
  extract(1:2)

[[1]]
# A tibble: 2 x 5
  date            x       y    ID   cut
  <date>      <dbl>   <dbl> <int> <int>
1 2010-12-26 73719. 803002.     1     1
2 2010-12-31 66825. 870527.     1     1

[[2]]
# A tibble: 2 x 5
  date            x       y    ID   cut
  <date>      <dbl>   <dbl> <int> <int>
1 2011-01-05 63023. 807545.     1     2
2 2011-01-10 76356. 875837.     1     2

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-12-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-27
    相关资源
    最近更新 更多