【发布时间】:2021-09-05 10:50:03
【问题描述】:
我正在尝试将数据集过滤到两个月内。我想过滤掉有数据的ID和year,并删除没有关联对的ID和year。
例如,如果 ID 和 year 在数据集中同时包含 1 月和 7 月月份,我想将 ID 和 year 包含在我的过滤数据中。如果ID 只有一月而不是七月,我想删除此数据而不将其包含在过滤数据集中。有没有好的方法来做到这一点?请注意,我不确定如何模拟示例中的不均匀数据集。
在筛选出我想要的输出后,我通过为每个季节性月份创建一个列表来进行测试,其中每个 ID 和 year 至少有 15 行与之关联。
library(lubridate)
library(dplyr)
set.seed(12345)
df <- tibble(
date = sample(seq(dmy("01-01-2010"), dmy("31-12-2013"), by = "days"),
1000, replace = TRUE),
x = runif(length(date), min = 60000, max = 80000),
y = runif(length(date), min = 800000, max = 900000),
ID = rep(1:5, 200),
month = month(date),
year =year(date)) %>%
arrange(ID, date)
df %>%
filter(month %in% c(1,7)) %>%
group_by(ID, year) %>%
mutate(complete = length(unique(month)) == 2) %>%
group_by(ID) %>%
filter(all(complete)) %>%
group_by(ID, year)
# Creates a list for each year and by ID
summer_list <- df %>%
filter(month %in% 7) %>%
filter(n() >= 15) %>%
group_split(year, ID)
# Renames the names in the list to AnimalID and year
names(summer_list) <- sapply(summer_list,
function(x) paste(x$ID[1],
x$year[1], sep = '_'))
# Creates a list for each year and by ID
winter_list <- df1 %>%
filter(month %in% 1) %>%
filter(n() >= 15) %>%
group_split(year, ID)
# Renames the names in the list to ID and year
names(winter_list) <- sapply(winter_list,
function(x) paste(x$ID[1],
x$year[1], sep = '_'))
【问题讨论】:
标签: r dplyr tidyverse lubridate tibble