overboard182
overboard182

Reputation: 300

Trying to find row associated with max value in dataframe R

Like the title says. I am having trouble. for example I have a 2 column (V1,V2) dataframe with lots of rows, around 300,000. I know that

max(df$V2) 

will give me the max value of that second column. Now that I know my max value, how can I get the entire row associated with that value. Thanks!

Upvotes: 1

Views: 7946

Answers (2)

nisetama
nisetama

Reputation: 8863

I needed to find the row and column name of the maximum value in a data frame, but I ended up using this:

t=data.frame(Altaian=c(0.044,0.011,0.007,0.018,0.010),
Kumyk=c(0.009,0.028,0.042,0.083,0.022),
Kyrgyz_Kyrgyzstan.DG=c(0.034,0.004,0.001,0.017,0.001),
row.names=c("Tatar_Mishar","Nogai_Astrakhan","Kyrgyz_Kyrgyzstan","Yakut","Uyghur.DG"))

max=which(t==max(t))[1]
c(rownames(t)[max%%nrow(t)],names(t)[max%/%nrow(t)+1]) #=> [1] "Yakut" "Kumyk"

Upvotes: 0

neringab
neringab

Reputation: 635

You have to write

df[which.max(df$V2), ]

If more than one row contains the max:

i <- max(df$V2) 
df[which(df$V2 == i), ]

Upvotes: 7

Related Questions