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

How to get the range based on a condition?

I want to get the range based on a condition. I tried using case_when() but failed. Here is what I tried:

library(tidyverse)

dat <- iris %>%
  as_tibble() %>%
  pivot_longer(!Species, names_to = "Variable", values_to = "Measure")

dat %>%
  filter(Variable == "Sepal.Length") %>%
  case_when(
    Species == "setosa" ~ range(.$Measure),
    Species == "versicolor" ~ range(.$Measure),
    Species == "virginica" ~ range(.$Measure)
  ) %>%
  setNames(unique(sort(dat$Species)))

The desired output is a named list with the ranges per species:

$setosa
[1]   4.3 5.8

$versicolor
[1]   4.9 7.0

$virginica
[1]   4.9 7.9

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

>Solution :

Since your output is a list rather than a dataframe, I guess we have to use either apply family or purrr::map.

library(tidyverse)

iris %>%
  as_tibble() %>%
  pivot_longer(!Species, names_to = "Variable", values_to = "Measure") %>% 
  filter(Variable == "Sepal.Length") %>% 
  split(.$Species) %>% 
  map(., ~range(.x$Measure))

$setosa
[1] 4.3 5.8

$versicolor
[1] 4.9 7.0

$virginica
[1] 4.9 7.9
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