【问题标题】:Keep values from a list based on the first timestamp record根据第一个时间戳记录保留列表中的值
【发布时间】:2020-01-27 20:58:32
【问题描述】:

我想保留外部列表:

list <- c("Google", "Yahoo", "Amazon")

数据框中的值记录在数据的第一个时间戳(最旧的时间戳)中,如下所示:

dframe <- structure(list(id = c(1L, 1L, 1L, 1L, 2L, 2L, 2L), name = c("Google", 
    "Google", "Yahoo", "Amazon", "Amazon", "Google", "Amazon"), date = c("2008-11-01", 
    "2008-11-02", "2008-11-01", "2008-11-04", "2008-11-01", "2008-11-02", 
    "2008-11-03")), class = "data.frame", row.names = c(NA, -7L))

预期的输出是这样的:

id   name       date
1 Google 2008-11-01
1  Yahoo 2008-11-01
1 Amazon 2008-11-04
2 Amazon 2008-11-01
2 Google 2008-11-02

怎么可能?

使用this,它只保留每个id的第一条记录,而不是列表中第一次记录的每个值

library(data.table)
setDT(dframe)
date_list_first = dframe[order(date)][!duplicated(id)]

【问题讨论】:

    标签: r date filter


    【解决方案1】:

    使用base R的选项

    dframe$date <- as.Date(dframe$date)
    aggregate(date~ ., dframe, min)
    #  id   name       date
    #1  1 Amazon 2008-11-04
    #2  2 Amazon 2008-11-01
    #3  1 Google 2008-11-01
    #4  2 Google 2008-11-02
    #5  1  Yahoo 2008-11-01
    

    【讨论】:

    【解决方案2】:

    这就是你可以在dplyr中做到的方式:

    dframe %>% mutate(date = as.Date(date)) %>%
    group_by(id, name) %>% summarise(date = min(date)) %>%
    ungroup()
    

    没什么特别的,只是分组和总结。

    输出

    # A tibble: 5 x 3
         id name   date      
      <int> <chr>  <date>    
    1     1 Amazon 2008-11-04
    2     1 Google 2008-11-01
    3     1 Yahoo  2008-11-01
    4     2 Amazon 2008-11-01
    5     2 Google 2008-11-02
    

    【讨论】:

      【解决方案3】:

      使用data.table:

      dframe = data.table(dframe)
      dframe[, date := as.Date(date)]
      
      dt = dframe[, .(date = min(date)), .(id, name)]
      
      > dt
         id   name       date
      1:  1 Google 2008-11-01
      2:  1  Yahoo 2008-11-01
      3:  1 Amazon 2008-11-04
      4:  2 Amazon 2008-11-01
      5:  2 Google 2008-11-02
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-09-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多