【问题标题】:Filter dates on a grouped dataset using dplyr使用 dplyr 过滤分组数据集上的日期
【发布时间】:2018-06-20 10:01:26
【问题描述】:

假设我有以下数据集:

library(dplyr)

name <- c("b", "a", "a", "b","b","a", "b", "c",  "c",  "c",  "c", "a")
class <- c(0, 1, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1)
date <- c("10-06-2018", "11-06-2018", "12-06-2018", "13-06-2018", "14-06-2018", "15-06-2018", "16-06-2018","17-06-2018", "18-06-2018", "19-06-2018", "20-06-2018", "21-06-2018")
dates <- as.Date(date, "%d/%m/%Y")
df <- data.frame(name, class, date)

df <- df %>%
  group_by(name) %>%
  arrange(date) %>%
  ungroup() %>%
  arrange(name)

我想过滤数据集,以便对于每个名称组,我都有第 0 类的最短日期和第 0 类之后的第 1 类的最短日期。在这种情况下,我会:

df.new <- df[c(2,3,5,6,9,11), ]

【问题讨论】:

  • 你应该使用dates &lt;- as.Date(date, "%d-%m-%Y"),否则它将不起作用。
  • 除了@Jaap 提到的,您需要将dates 分配给数据框,而不是date

标签: r filter dplyr


【解决方案1】:

可能有更简洁的解决方案,但解决方法如下

#split into two dataframes
# find the min dates for class == 0
df0 <- df %>%
 filter(class == 0) %>%
 group_by(name) %>%
 summarise(dates0 = min(dates))

# find min date of class == 1 that is coming after class == 0
# and join the two dataframes
df1 <- df %>%
 filter(class == 1) %>%
 select(-class) %>%
 left_join(df0, by = 'name')

# keep only the relevant dates     
df1 <- df1 %>%
 mutate(dates1 = ifelse(dates > dates0, 1, 0)) %>%
 filter(dates1 != 0) %>%
 group_by(name) %>%
 summarise(dates = min(dates)) %>%
 mutate(class = 1)

# combine the two dataframes into one with the correct dates
df <- df0 %>%
 mutate(class = 0) %>%
 rename(dates = dates0) %>%
 bind_rows(df1) %>%
 group_by(name) %>%
 arrange(dates) %>%
 ungroup() %>%
 arrange(name)

【讨论】:

  • 谢谢,非常感谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-17
  • 2018-06-02
  • 1970-01-01
  • 1970-01-01
  • 2018-02-01
  • 1970-01-01
相关资源
最近更新 更多