Home > Mobile >  For each column, find row name for max value and store in a data frame
For each column, find row name for max value and store in a data frame

Time:10-29

I have this dataset (104x182) and for each column, I want to find the row index for the max value within that column.

This is what I have so far:

library(tibble)

p=1:182
DF <- tibble(i=as.numeric(), max=as.numeric())
for (i in p){
  max <- which.max(Z0[, p])
  DF <- DF %>%
    add_row(i=i, max=max)
}

DF %>%
  filter(max != 1) %>%
  distinct(max, .keep_all=TRUE)

When I try run the for loop, I get the following error:

Error in which.max(Z0[, p]) : 
  'list' object cannot be coerced to type 'double'

How can I change the above code so that it works.

CodePudding user response:

If you are looking for the index of max value in each column, I think this is what you are looking for:

set.seed(123)
#test data
df<- as.data.frame(matrix(as.integer(runif(200, 0, 100)), ncol=10))

#row index of max value in each column
answer <- apply(df, MARGIN = 2, which.max)

answer
# V1  V2  V3  V4  V5  V6  V7  V8  V9 V10 
# 11   4  19   5   7   4   6   5  19  13 

CodePudding user response:

We could use max.col in base R

max.col(t(df1), "first")
  • Related