试图在数据帧R中找到与最大值相关联的行

时间:2016-04-22 20:24:50

标签: r dataframe max row

就像标题所说的那样。我遇到了麻烦。例如,我有一个2列(V1,V2)数据框,有很多行,大约300,000。我知道

max(df$V2) 

将为我提供第二列的最大值。现在我知道了我的最大值,我怎样才能得到与该值相关的整行。谢谢!

2 个答案:

答案 0 :(得分:3)

你必须写

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

如果多行包含max:

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

答案 1 :(得分:0)

我需要在数据框中找到最大值的行名和列名,但我最终使用了这个:

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"