Finding the maximum value of a variable

Viewed 230

I would like to find the maximum value of a variable (column) and then retain this value (the maximum value) and all values below it. Along with these values, I would like to retain the corresponding values from all other variables (columns) within the data frame. I want to exclude all values above this point from the data frame, for all variables within it. Included is the script for an example data frame (df), and an expected data frame (df2) i.e. what I am trying to achieve. I would be so grateful for some script to do this.

Ba <- c(1,1,1,2,2)
Sr <- c(1,1,1,2,2)
Mn <- c(1,1,2,1,1)
df <- data.frame(Ba, Sr, Mn)

df

#   Ba Sr Mn
# 1  1  1  1
# 2  1  1  1
# 3  1  1  2
# 4  2  2  1
# 5  2  2  1

Showing 1 to 5 of 5 entries, 3 total columns

This is what I want to achieve in R:

Ba2 <- c(1,2,2)
Sr2 <- c(1,2,2)
Mn2 <- c(2,1,1)
df2 <- data.frame(Ba2, Sr2, Mn2)

df2

#   Ba2 Sr2 Mn2
# 1   1   1   2
# 2   2   2   1
# 3   2   2   1

Showing 1 to 3 of 3 entries, 3 total columns

3 Answers

You can subset df with the sequence from min to nrow(df) of which.max per column:

df[min(sapply(df, which.max)):nrow(df),]
#  Ba Sr Mn
#3  1  1  2
#4  2  2  1
#5  2  2  1

Does this work:

df[max(apply(df, 1, which.max)):nrow(df),]
  Ba Sr Mn
3  1  1  2
4  2  2  1
5  2  2  1

Using cummax

library(dplyr)
library(purrr)
df %>% 
   filter(cummax(invoke(pmax, cur_data())) == max(cur_data()))
  Ba Sr Mn
1  1  1  2
2  2  2  1
3  2  2  1
Related