【问题标题】:How do I drop all the rows within a group when one of the observations meets a certain condition?当其中一个观察满足特定条件时,如何删除组中的所有行?
【发布时间】:2021-10-23 03:11:37
【问题描述】:

我需要知道如何删除 data.frame (DF1) 中某个点之前的所有行

我想删除编号最小的行之前的所有行(按ID分组并按日期排列)

DF1
ID     Date       Value
1      2/11/2021  0    
1      2/12/2021  2         
1      2/13/2021  1            
1      2/14/2021  0            
1      2/15/2021  1            
1      2/16/2021  -37            
1      2/17/2021  0           
1      2/18/2021  1            
1      2/19/2021  -2

我试图到达的数据框(DF2):

DF2
ID     Date       Value       
1      2/16/2021  -37            
1      2/17/2021  0           
1      2/18/2021  1            
1      2/19/2021  -2

谢谢!

【问题讨论】:

    标签: r dataframe dplyr


    【解决方案1】:

    你可以使用 -

    library(dplyr)
    
    df %>% 
      mutate(Date = as.Date(Date, '%m/%d/%Y')) %>%
      arrange(ID, Date) %>%
      group_by(ID) %>% 
      slice(which.min(Value):n()) %>%
      ungroup
    
    
    #     ID Date       Value
    #  <int> <date>     <int>
    #1     1 2021-02-16   -37
    #2     1 2021-02-17     0
    #3     1 2021-02-18     1
    #4     1 2021-02-19    -2
    

    【讨论】:

      【解决方案2】:

      我们可以做

      library(dplyr)
      library(lubridate)
      DF1 %>%
          arrange(ID, mdy(Date)) %>%
          group_by(ID) %>% 
          slice(match(min(Value), Value):n()) %>% 
          ungroup
      # A tibble: 4 × 3
           ID Date      Value
        <int> <chr>     <int>
      1     1 2/16/2021   -37
      2     1 2/17/2021     0
      3     1 2/18/2021     1
      4     1 2/19/2021    -2
      

      数据

      DF1 <- structure(list(ID = c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), Date = c("2/11/2021", 
      "2/12/2021", "2/13/2021", "2/14/2021", "2/15/2021", "2/16/2021", 
      "2/17/2021", "2/18/2021", "2/19/2021"), Value = c(0L, 2L, 1L, 
      0L, 1L, -37L, 0L, 1L, -2L)), class = "data.frame", row.names = c(NA, 
      -9L))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-02-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多