【问题标题】:Removing extra elements in a list based on another list根据另一个列表删除列表中的额外元素
【发布时间】:2021-11-25 00:18:13
【问题描述】:

我有一个数据集,我尝试将其分成两个列表。在每个列表中,它包含一个元素(例如,列表对象中的[[1]][[2]][[3]]),用于 10 天间隔内的单个 ID(例如,[[1]] 中的第 1-10 天,11 [[2]] 中的 -21,[[3]] 中的 22-31)。

在下面的示例代码中,jan 的列表对于每个 ID 具有三个间隔(例如,A 具有三个间隔的三个元素,B 具有三个间隔的三个元素,@987654332 @ 具有三个间隔的三个元素)。 july 的列表对于每个 ID 只有 2 个间隔,这对我来说是个问题(例如,它在列表对象中只包含 [[1]][[2]] 而不是三个)。

我试图弄清楚如何删除jan 中与july 的间隔不对应的额外间隔。例如,对于IDA,我想创建一个函数来比较两个列表,并删除jan 中的第三个区间(july 中的缺失区间)。我该怎么做?

library(lubridate)
library(tidyverse)
date <- rep_len(seq(dmy("01-01-2010"), dmy("20-07-2010"), by = "days"), 600)
ID <- rep(c("A","B","C"), 200)

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

df$month <- month(df$date)

jan <- df %>%
  mutate(new = floor_date(date, "10 days")) %>%
  group_by(ID) %>% 
  mutate(new = if_else(day(new) == 31, new - days(10), new)) %>% 
  group_by(new, .add = TRUE) %>%
  filter(month == "1") %>% 
  group_split()

july <- df %>%
  mutate(new = floor_date(date, "10 days")) %>%
  group_by(ID) %>% 
  mutate(new = if_else(day(new) == 31, new - days(10), new)) %>% 
  group_by(new, .add = TRUE) %>%
  filter(month == "7") %>% 
  group_split()

【问题讨论】:

  • 很难理解你实际上想要完成什么。你说的元素是什么意思?你说的间隔是什么意思?我怀疑你没有收到答复的原因是不清楚你在追求什么。

标签: r list dplyr lubridate


【解决方案1】:

我仍然不确定你到底在追求什么。无论如何,这段代码可以满足您的要求。

df2 <- bind_rows(jan, july) %>%
  # adding a helper variable to distinguish if a day from the date component is
  # 10 or lower, 20 or lower or the rest 
  mutate(helper = ceiling(day(date)/10) %>% pmin(3)) %>% 
  group_by(ID, helper) %>%
  # adding another helper finding out how may distinct months there are in the subgroup
  mutate(helper2 = n_distinct(month)) %>% ungroup() %>%
  filter(helper2 == 2) %>%
  # getting rid of the helpers
  select(-helper, -helper2) %>%
  group_by(ID, new)

jan2 <- df2 %>%
  filter(month == "1") %>% 
  group_split()

【讨论】:

    猜你喜欢
    • 2015-09-20
    • 1970-01-01
    • 1970-01-01
    • 2018-08-07
    • 2019-10-24
    • 2018-07-14
    • 1970-01-01
    • 2022-11-13
    • 1970-01-01
    相关资源
    最近更新 更多