代码之家  ›  专栏  ›  技术社区  ›  DN98024

如何在R中过滤掉其他所有内容的同时保持值的首次出现?

  •  0
  • DN98024  · 技术社区  · 1 年前

    这是我当前数据集的外观。我想包括患者1的数据,直到第一个“1”出现在“test.result”中,然后删除有关患者1的任何信息。

    current dataset

    这就是我迄今为止所尝试的——它删除了我数据中的所有0值,但在第一个初始值1之后没有删除每个患者的所有其他1值。 如果患者的0值前面没有1,我想保留0值。

    new.ddset <- ddset %>% 
      group_by(id) %>% 
      filter(test.result == max(test.result))
    

    这就是我想要的结果:
    例如:对于id1,在screen.num 1-5处,test.result为0,但在屏幕6处,screen.num为1-我想将该id的所有信息保留到屏幕6,然后删除id1的所有其他id信息。

    1 回复  |  直到 1 年前
        1
  •  0
  •   Edward    1 年前

    请尝试以下操作。

    filter(df, cumsum(test.result)<=1  
           & test.result==cummax(test.result), .by=ID)
    

      ID seq test.result
    1  1   1           1
    2  2   1           0
    3  2   2           1
    4  3   1           0
    5  3   2           0
    6  3   3           0
    7  3   4           1
    

    数据

    df
       ID seq test.result
    1   1   1           1
    2   1   2           0
    3   1   3           1
    4   1   4           0
    5   1   5           0
    6   2   1           0
    7   2   2           1
    8   2   3           0
    9   2   4           0
    10  3   1           0
    11  3   2           0
    12  3   3           0
    13  3   4           1
    
    df <- structure(list(ID = c(1, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3), 
        seq = c(1, 2, 3, 4, 5, 1, 2, 3, 4, 1, 2, 3, 4), test.result = c(1, 
        0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1)), class = "data.frame", row.names = c(NA, 
    -13L))