Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in R Programming by (50.2k points)

From the following data frame, I just want to find the row name based on just cell value, which doesn't work when different cells can have the same values:

   |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 tried the following ways, 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))

1 Answer

0 votes
by (107k points)

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, just 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"))

If you are a beginner and want to know more about R then do check out the R programming course that will help you in understanding R from scratch. 

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...