My R data.frame df
looks like:
Name Amount
1 "A" 150
2 "B" 120
3 "C" "NA"
4 "D" 160
.
.
.
I want to get the Name and Amount row when I do something like min(df$Amount)
.
That gets me the minimum number in the Amount column, but how do I get the Name in that same row? Or the entire row for that matter?
Name should be "B" in this case.
Similar to Select * Where Amount = min(Amount)
What is the best way to do this in R?
@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)), ]
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments