rgroupingminimumgroup-summaries

How to find minimum within group value greater than certain value in r


I have the following data frame:

  PATIENT_ID VALUE
  1          8
  1          16
  1          24 
  2          50 
  2          56
  3          2
  3          70

Now I want to find all PATIENT_IDs that have a minimum that is greater than 48. In this example, the minimum of Patient 1,2,3 are 8, 40 and 2 respectively. So, it should return only PATIENT_ID = 2, since that is the only PATIENT_ID that has a minimum greater than 48.


Solution

  • Allow for grouping with by:

     by(data = df, INDICES = df$PATIENT_ID, FUN = function(x){ifelse(min(x$VALUE) > 48, min(x$VALUE), FALSE)})
    

    which gives:

    df$PATIENT_ID: 1
    [1] 0
    ------------------------------------------------------------------------------------------- 
    df$PATIENT_ID: 2
    [1] 50
    ------------------------------------------------------------------------------------------- 
    df$PATIENT_ID: 3
    [1] 0