Return row of Data Frame based on value in a column - R

后端 未结 4 999
無奈伤痛
無奈伤痛 2021-01-31 09:43

My R data.frame df looks like:

     Name     Amount
1    \"A\"      150
2    \"B\"      120
3    \"C\"      \"NA\"
4    \"D\"      160
.
.
.
         


        
相关标签:
4条回答
  • 2021-01-31 10:16

    You could use dplyr:

    df %>% group_by("Amount") %>% slice(which.min(x))
    
    0 讨论(0)
  • 2021-01-31 10:18

    Based on the syntax provided

     Select * Where Amount = min(Amount)
    

    You could do using:

     library(sqldf)
    

    Using @Kara Woo's example df

      sqldf("select * from df where Amount in (select min(Amount) from df)")
      #Name Amount
     #1    B    120
     #2    E    120
    
    0 讨论(0)
  • 2021-01-31 10:21

    Use which.min:

    df <- data.frame(Name=c('A','B','C','D'), Amount=c(150,120,175,160))
    df[which.min(df$Amount),]
    
    > df[which.min(df$Amount),]
      Name Amount
    2    B    120
    

    From the help docs:

    Determines the location, i.e., index of the (first) minimum or maximum of a numeric (or logical) vector.

    0 讨论(0)
  • @Zelazny7's answer works, but if you want to keep ties you could do:

    df[which(df$Amount == min(df$Amount)), ]
    

    For example with the following data frame:

    df <- data.frame(Name = c("A", "B", "C", "D", "E"), 
                     Amount = c(150, 120, 175, 160, 120))
    
    df[which.min(df$Amount), ]
    #   Name Amount
    # 2    B    120
    
    df[which(df$Amount == min(df$Amount)), ]
    #   Name Amount
    # 2    B    120
    # 5    E    120
    

    Edit: If there are NAs in the Amount column you can do:

    df[which(df$Amount == min(df$Amount, na.rm = TRUE)), ]
    
    0 讨论(0)
提交回复
热议问题