James Marshall
James Marshall

Reputation: 91

R How to select an observation from a data frame which is False and has the min value

I have a data frame with three columns and i would like to select the observation that has the value FALSE in the column TEST and also has the minimum value at the Power column. I tried which(kolibri[ ,"TEST"] == FALSE) && which(kolibri[ , "Power"] == min(kolibri[ , "Power"]))but no luck it returns TRUE but i want the index of the observation. My data frame is like this:

Variable_Name Power TEST
  A             2    true
  B             45   false
  C             33   false
  D             25   false
  E             15   true

in this case i want to have the index of the variable D

Upvotes: 0

Views: 1711

Answers (2)

Colonel Beauvel
Colonel Beauvel

Reputation: 31171

If your data.frame is df:

with(df, by(Power,TEST, FUN=min)['false'])
#false 
#   25 

If you want the full line:

with(df, df[Power==by(Power,TEST, FUN=min)['false'],])
#  Variable_Name Power  TEST
#4             D    25 false

If you want the index:

which.max(with(df, Power==by(Power,TEST, FUN=min)['false']))
#[1] 4

If you have FALSE and TRUE in your data.frame TEST column:

which.max(with(df, Power==min(Power[!TEST])))
#[1] 4

Upvotes: 3

Heroka
Heroka

Reputation: 13149

If TEST is not a boolean: transform it

kolibri$TEST <- as.logical(kolibri$TEST)

Then put everything in a call to which (used 25 as your other data are unavailable here)

   > which(kolibri$TEST == FALSE & kolibri$Power== 25)
[1] 4

Using OP's own example (which I cannot run on my machine), code would be:

which(kolibri$TEST == FALSE & kolibri$Power== min(fevgeis1$Power))

Upvotes: 1

Related Questions