Finding Row Index Containing Maximum Value Using R

How to extract the row with min or max values?

You can include your which.max call as the first argument to your subsetting call:

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

Finding index corresponding to the maximum value

which.max works well with dplyr grouping:

library(dplyr)

Data %>% group_by(Order_Year) %>%
summarise(by.Yen = Ship_Year[which.max(Yen)],
by.Units = Ship_Year[which.max(Units)])

## # A tibble: 4 × 3
## Order_Year by.Yen by.Units
## <dbl> <dbl> <dbl>
## 1 1999 NA NA
## 2 2000 1997 1997
## 3 2001 1998 1998
## 4 2002 1997 1997

R: how to find the indices of the maximal value per column

transpose mat and use max.col

i = max.col(t(mat))
v = t(mat)[cbind(seq(NCOL(mat)), i)]
v
# [1] 7 8 6
i
# [1] 2 2 3

Return Index Row Number of N Minimum/Maximum Value for Each Column of Matrix

To get the index of the highest and lowest values

apply(m1, 2, which.max)
apply(m1, 2, which.min)

If we are interested in 2nd highest, 2nd lowest etc

apply(m1, 2, function(x) order(x)[2])

Or use sort with index.return = TRUE

apply(m1, 2, function(x) sort(x, index.return = TRUE))

and then extract the index of interest

apply(m1, 2, function(x) {i1 <- sort(x, index.return = TRUE)$ix
i1[i1 < 3]
})

If we need the row index

getrowIndexEachCol <- function(mat, n, isMax = TRUE) {
if(!isMax) mat <- -mat
apply(mat, 2, function(x) {i1 <- rank(x)
i1[i1 <= n]
})
}
getrowIndexEachCol(m1, 2)

The difference would be noticed using a different dataset

m2 <- cbind(c(7, 3, 5, 8, 11), c(4, 8, 6, 5, 3))
getrowIndexEachCol(m2, 3)

find max value's column index and row index individually in R

For a large matrix which.max should be more efficient than which. So, for a matrix m, we can use

A = row(m)[d <- which.max(m)]
B = col(m)[d]

Trying to find row associated with max value in dataframe R

You have to write

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

If more than one row contains the max:

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

Find Max value and Item containing the max value for each row


library(tidyverse)
df1 %>% 
rowid_to_column() %>%
unite(Item, Item1, Item2, Item3, Item4) %>%
unite(Qty, Qty1, Qty2, Qty3, Qty4) %>%
separate_rows(2:3, sep = "_") %>%
mutate(Qty = as.numeric(Qty)) %>%
group_by(rowid) %>%
filter(Qty == max(Qty, na.rm = TRUE))
#> # A tibble: 5 x 3
#> # Groups: rowid [3]
#> rowid Item Qty
#> <int> <chr> <dbl>
#> 1 1 SUV2 5
#> 2 1 SUV3 5
#> 3 2 SUV4 7
#> 4 3 SUV3 5
#> 5 3 PNC3 5


Or instead of filter(Qty == max(Qty, na.rm = TRUE)) in the last line:

              ... %>% 
arrange(-Qty) %>%
slice(1)

to get:

# # A tibble: 3 x 3
# # Groups: rowid [3]
# rowid Item Qty
# <int> <chr> <dbl>
# 1 1 SUV2 5
# 2 2 SUV4 7
# 3 3 SUV3 5
# Warning message:
# NAs introduced by coercion

Data:

df1 <- read.table(text="Item1   Qty1    Item2   Qty2    Item3   Qty3    Item4   Qty4
SUV1 4 SUV2 5 SUV3 5 SUV4 3
SUV4 7 PLV4 3 PNC5 6 NA NA
SUV3 5 PNC3 5 NA NA NA NA",
header=T)


Related Topics



Leave a reply



Submit