简体   繁体   中英

How to find the max value in a list and its row and column index in R?

I have a list like this:

> A
 [[1]]
            Jan Feb Mar
Product_A   14   7  90 
Product_B    1   2   3

 [[2]]
            Jan Feb Mar
Product_C   15   7   9

I want to have the max value in this list and its row and column names. I would like to see something like this: 90, Product_A, Mar I really appreciate it if somebody could help me with this. Thanks

To me it is unclear whether you want to names of the max value of the whole list or of every dataframe inside the list. There is already an answer from @RonakShah for the latter interpretation, so I post one if you look for names of one max value of the whole list. Using list.which and the idea of a similiar question you can do

library(rlist)
library(reshape2)

max_val <- max(unlist(list_df))
which_list <- list.which(list_df, max(Jan, Feb, Mar) == max_val)
df <- list_df[[which_list]]

subset(melt(as.matrix(df)), value == max_val)
Var1       Var2   value
Product_A  Mar    90

As @r2evans mentioned, we can try to find out how to solve it for one matrix/dataframe and then use lapply to apply it to list of dataframes. Assuming your list is called list_df one way would be

get_max_row_col <- function(x) {
   val <- max(x, na.rm = TRUE)
   arr <- which(x == val, arr.ind = TRUE)
   data.frame(value = val, rowname = rownames(x)[arr[, 1]], 
              column_name = colnames(x)[arr[, 2]])
}
do.call(rbind, lapply(list_df, get_max_row_col))

#  value   rowname column_name
#1    90 Product_A         Mar
#2    15 Product_C         Jan

We can also use purrr 's map_df or map_dfr with the same function

purrr::map_df(list_df, get_max_row_col)

As @schwantke points out that if you want to find one maximum value in the entire dataframe you can skip the lapply part bind all the dataframe together in one list and perform the calculation.

df1 <- do.call(rbind, list_df)
val <- max(df1)
arr <- which(df1 == val, arr.ind = TRUE)
data.frame(value = val, rowname = rownames(df1)[arr[, 1]], 
           column_name = colnames(df1)[arr[, 2]])

#  value   rowname column_name
#1    90 Product_A         Mar

data

list_df <- list(structure(list(Jan = c(14L, 1L), Feb = c(7L, 2L), Mar = c(90L, 
3L)), class = "data.frame", row.names = c("Product_A", "Product_B"
)), structure(list(Jan = 15L, Feb = 7L, Mar = 9L), 
class = "data.frame", row.names = "Product_C"))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM