Home > OS >  How to get the range based on a condition?
How to get the range based on a condition?

Time:08-24

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

CodePudding user response:

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
  • Related