Home > Software design >  How to return the name of a row that is not the first, that has a maximum value in a column in r?
How to return the name of a row that is not the first, that has a maximum value in a column in r?

Time:10-26

data <- data.frame(Item = c(1, 2, 3),
                  Year = c(2001, 2002, 2003),
                   X    = c(3, 2, 45),

I want to return the year with the highest value in column X. I have tried using rownames() but it returns the number 3 instead of the year 2003. This is not a duplicate question to Retrieve row names of maximum and second maximum values of a column in R because I want to retrieve the name of a row that is not the first row.

CodePudding user response:

> data[which.max(data$X), ]
  Item Year  X
3    3 2003 45

If you only want to return the year:

> data[which.max(data$X), "Year"]
[1] 2003

Since you did not provide an expected output, we can consider this option to get the corresponding rowname:

library(dplyr)
data %>% 
  mutate(row = rownames(.) ) %>% 
  slice(which.max(X)) %>% 
  select(row)
  • Related