Reputation: 21
Say I have this data frame df
:
|c1 |c2 |c3 |c4 |
r1 | 2 | 3 | 3 | 5 |
r2 | 5 | 8 | 6 | 1 |
Note that all the column values are unique, but some cell values repeat (3
and 5
). I'd like to find out the name of the row containing 5
in column c4
(in this case, it would return "r1"
).
I've found SO questions about finding the row name based on just cell value, which doesn't work when different cells can have the same values. I've also found questions about finding the row index based on the cell value and column index, but I need to be able to do this in a scenario where I might know the indices that correspond to the column/row names. But based on the answers I found for those questions, I've tried the following 4 methods, and none have worked:
# 1
df[max(df$c4), "c4"]
# 2
which(df == max(df$c4), arr.ind=TRUE)
# 3
rownames(df)[max(df$c4), "c4"]
# 4
row(df$c4, max(df$c4))
Thanks in advance!
Upvotes: 1
Views: 2064
Reputation: 388982
If you want row name based on max value in c4
use :
rownames(df)[which.max(df$c4)]
#[1] "r1"
Or if there could be multiple max value use :
rownames(df)[df$c4 == max(df$c4)]
data
df <- structure(list(c1 = c(2L, 5L), c2 = c(3L, 8L), c3 = c(3L, 6L),
c4 = c(5L, 1L)), class = "data.frame", row.names = c("r1", "r2"))
Upvotes: 2