user13243578
user13243578

Reputation:

How to find the highest number of a column and print two columns of that row in R?

How do get the highest value of column2 then print column1 AND column2 of that row?

Column1 Column2
test1    2
test2    9
test3    3
test5    4.5

So, how do I print the second row since column 2 has the highest value?

Remember that there are more columns in the data set but I don't wanna print them all.

EDIT: Already tried getting the highest value of that column but I would like to print two columns of that row (not all columns); the one below gives me the entire row which contains around 35 columns:

subset(df1, Column2 == max(Column2))

Upvotes: 0

Views: 60

Answers (1)

akrun
akrun

Reputation: 887881

We can use slice - returns the first row where the max value is found

library(dplyr)
df1 %>%
  select(Column1, Column2) %>%
  slice(which.max(Column2))

Or with subset from base R - returns all rows where the max value is present

subset(df1, Column2 == max(Column2), select = c(Column1, Column2))

Or with which.max - returns the first row where the max value is found

df1[which.max(df1$Column2),c("Column1", "Column2"), drop = FALSE]

Upvotes: 0

Related Questions