【问题标题】:Keep only common dates using dplyr package使用 dplyr 包仅保留常见日期
【发布时间】:2023-01-14 22:28:39
【问题描述】:

我有一个包含 3 列的数据框:站点、日期时间和英里数。我想保留每个站具有共同日期时间的行。

为了更清楚,我创建了一个可重现的示例

library(tidyverse)
library(lubridate)

df <- data.frame(station = c("A","A","A","B","B","B",
                                  "C","C","C"),
  date = c("1998-05-03","1999-06-01","2000-03-02",
           "1998-05-03","1999-06-01","2000-03-02",
           "1998-05-03","1999-06-01","2000-04-15"),
                      time  = c("00:00:10","00:00:20","00:00:50",
                                "00:00:10","00:00:20","00:00:40",
                                "00:00:34","00:00:20","00:00:40"),
                      miles = rnorm(9))

df <- df %>% 
  mutate(datetime = paste(date,time,sep = " "),
         datetime = as_datetime(datetime)) %>% 
  select(station,datetime,miles)
station datetime miles
A 1998-05-03 00:00:10 1.8587913
A 1999-06-01 00:00:20 0.1271054
A 2000-03-02 00:00:50 1.4531250
B 1998-05-03 00:00:10 0.3544122
B 1999-06-01 00:00:20 0.1033785
B 2000-03-02 00:00:40 0.9861990
C 1998-05-03 00:00:34 1.5029350
C 1999-06-01 00:00:20 1.1215914
C 2000-04-15 00:00:40 0.5222949

理想的输出

station datetime miles
A 1998-05-03 00:00:10 1.8587913
A 1999-06-01 00:00:20 0.1271054
B 1998-05-03 00:00:10 0.3544122
B 1999-06-01 00:00:20 0.1033785
C 1999-06-01 00:00:20 1.1215914

我尝试了以下代码,但没有用:

df %>%
  filter(station %in% (split(df$station, df$datetime) %>% reduce(intersect)))

你有什么建议吗? (我更喜欢 dplyr 解决方案,但任何解决方案都可以接受)

【问题讨论】:

    标签: r dplyr


    【解决方案1】:

    请尝试

    df2 <- df %>% dplyr::arrange(date, time) %>% 
    dplyr::group_by(date,time) %>% mutate(n=n()) %>% 
    filter(n>1) %>% dplyr::arrange(station) 
    

    【讨论】:

      猜你喜欢
      • 2020-05-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-17
      • 1970-01-01
      • 2023-04-07
      • 2019-07-28
      • 2013-02-27
      相关资源
      最近更新 更多