Search code examples
rindexingranking

Index lowest value as second criterion


I'd like to select a value (Z) from a data frame via an index where 1) the column Y=="A" and 2) the column X is the lowest possible

for following data frame the value "30" (from column Z) should be return:

X=seq(1,5)
Y=c("A","A","B","B","C")
Z=seq(10,50,10)
df <- data.frame(X,Y,Z)

df[df$Y=="B" & ???,"Z"]

Can that be done within one step or do I have to select first for "B" and then for lowest in a second step?


Solution

  • A bit clunky to put all in one line, but you can do this:

    df[df$Y=="B" & df$X == min(df$X[df$Y=='B']), "Z"]
    

    or

    df[with(df, Y=='B' & X == min(X[Y=='B'])), 'Z']