Peter Lawrence
Peter Lawrence

Reputation: 749

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.

Upvotes: 1

Views: 777

Answers (3)

Jason
Jason

Reputation: 2597

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

Upvotes: -1

arvchi
arvchi

Reputation: 61

There are many ways to do this. One way is to first filter out rows that don't match your criteria, and then return the PATIENT_IDs of the remaining rows.

df <- df[df$value > 48,]
df$PATIENT_ID

Upvotes: 1

AidanGawronski
AidanGawronski

Reputation: 2085

unique(your_df[your_df$VALUE > 48, "PATIENT_ID"])

Upvotes: 2

Related Questions