'Can I slice a data frame using an ifelse function?

I have a big data frame, and I only want a single line from it, if a certain condition of x >= 4 is met. However, out of my 50 entries, 43 reach x >= 4. For the others, I want to take the highest value it reaches for x. So, I want to create code which will filter for x >= 4 and take that value, unless 4 is not reached, and then I want the tail_end.

I currently have the following code, and I am not sure how to incorporate the ifelse statement:

selection_T01 <- df_T01 %>%
        group_by(id) %>%
        filter(X >= 0) %>%
        slice(1) %>%
        ungroup()


Solution 1:[1]

The idea is to create a separate condition column and use that as a grouping variable. I recommend the nest-map-unnest approach when dealing with groups of dataframes.

library(dplyr)
library(tidyr)
library(purrr)

get_selection <- function(condition, df) {
  func_slice <- ifelse(
    condition, 
    slice_max,
    slice_min
  )
  
  func_slice(df, Sepal.Length)
}

selection <- iris |> 
  mutate(
    condition = Sepal.Length > 6
  ) |> 
  group_by(Species, condition) |> 
  nest() |> 
  mutate(
    selection = map2(condition, data, get_selection)
  ) |> 
  select(-data) |> 
  unnest(cols = c(selection))

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Evan Cutler Anway