Home > Blockchain >  Find min and max of a column given an ordered index in Dplyr
Find min and max of a column given an ordered index in Dplyr

Time:12-31

I have a vector and I add his indexes like it follows:

library(tidyverse)
## Create the vector
vector_ex <- c(44, 30, 24, 32, 35)
## Add indexes 
vector_ex_indexed <- cbind( seq_along(vector_ex), vector_ex)

as.data.frame(vector_ex_indexed) %>%
  rename(Index = V1) 

  Index vector_ex
1     1        44
2     2        30
3     3        24
4     4        32
5     5        35

I would like to find the first minimum value of vector_ex taking into account the order of the Index and the first maximum value of vector_ex just after the index attached to the minimum.

For example in this case I want to identify - with dplyr:

  • the first pair Index & vector_ex with the minimum value is:

    Index vector_ex
    3     3        24
    
  • the first pair Index & vector_ex with the maximum value is:

    Index vector_ex
    5     5        35
    

CodePudding user response:

One option could be:

df %>%
    slice(which.min(vector_ex):n()) %>%
    slice(c(1, which.max(vector_ex)))

  Index vector_ex
1     3        24
2     5        35

CodePudding user response:

Another solution would be with filter:

library(tidyverse)
df %>%
  filter(vector_ex == min(vector_ex) |
         vector_ex == max(vector_ex[Index > Index[which.min(vector_ex)]]))

  Index vector_ex
1     3        24
2     5        35
  • Related