Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  • 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
    

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading