Trying to Find Row Associated with Max Value in Dataframe 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),]

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), ]

Get the rownumber a variable reached the max value in a data.frame column R

Simply using dplyr::across

library(dplyr)
Data %>%
summarise(across(everything(), ~which.max(.x)))

V1 v2 v3
1 5 5 3

Or using sapply,

sapply(Data, function(x) which.max(x))

V1 v2 v3
5 5 3

Select the row with the maximum value in each group

Here's a data.table solution:

require(data.table) ## 1.9.2
group <- as.data.table(group)

If you want to keep all the entries corresponding to max values of pt within each group:

group[group[, .I[pt == max(pt)], by=Subject]$V1]
# Subject pt Event
# 1: 1 5 2
# 2: 2 17 2
# 3: 3 5 2

If you'd like just the first max value of pt:

group[group[, .I[which.max(pt)], by=Subject]$V1]
# Subject pt Event
# 1: 1 5 2
# 2: 2 17 2
# 3: 3 5 2

In this case, it doesn't make a difference, as there aren't multiple maximum values within any group in your data.

how to keep only rows that have highest value in certain column in R

An easier approach is with max.col in base R. Select the columns that are numeric. Get the column index of each row where the value is max. Check if that is equal to 1 i.e. the first column (as we selected only from 2nd column onwards) and subset the rows

subset(df, max.col(df[-1], 'first') == 1)
# A tibble: 2 x 5
# Species North South East West
# <chr> <dbl> <dbl> <dbl> <dbl>
#1 a 4 3 2 3
#2 D 3 2 2 2

If it is based on the rowwise mean

subset(df, North > rowMeans(df[-1]))

Or if we prefer to use dplyr

library(dplyr)
df %>%
filter(max.col(cur_data()[-1], 'first') == 1)

Similarly if it based on the rowwise mean

df %>% 
filter(North > rowMeans(cur_data()[-1]))

Finding the maximum value for each row and extract column names

You can use apply like

maxColumnNames <- apply(x,1,function(row) colnames(x)[which.max(row)])

Since you have a numeric matrix, you can't add the names as an extra column (it would become converted to a character-matrix).
You can choose a data.frame and do

resDf <- cbind(data.frame(x),data.frame(maxColumnNames = maxColumnNames))

resulting in

resDf
A B C maxColumnNames
X 1 4 7 C
Y 2 5 8 C
Z 3 6 9 C

Add a variable to a data frame containing max value of each row

You can use apply. For instance:

df[, "max"] <- apply(df[, 2:26], 1, max)

Here's a basic example:

> df <- data.frame(a=1:50, b=rnorm(50), c=rpois(50, 10))
> df$max <- apply(df, 1, max)
> head(df, 2)
a b c max
1 1 1.3527115 9 9
2 2 -0.6469987 20 20
> tail(df, 2)
a b c max
49 49 -1.4796887 10 49
50 50 0.1600679 13 50


Related Topics



Leave a reply



Submit