Home > Net >  Using pipe (%>%) based on function parameter?
Using pipe (%>%) based on function parameter?

Time:06-08

I'm trying to conditionally add the pipe to make a slice max or slice min, based on the function parameter. Could you help me?

library(magrittr)

generates_data_graph <- function(data, positive = FALSE) { 

 data_graph <- data %>%
    {if (positive)
        slice_max(order_by = value1, n = 5) %>% 
        mutate(chave1 = fct_reorder(.f = key1, .x = value2, .desc = TRUE))  
     else 
        slice_min(order_by = value1, n = 5) %>% 
        mutate(chave1 = fct_reorder(.f = key1, .x = value2, .desc = FALSE)) 
    }
}

Another question, this will slow my code? Because this can be done by:

generates_data_graph <- function(data, positive = FALSE) { 


   if (positive) {
        data_graph <- data %>%
        slice_max(order_by = value1, n = 5) %>% 
        mutate(chave1 = fct_reorder(.f = key1, .x = value2, .desc = TRUE))

   }

   else {
        data_graph <- data %>%
        slice_min(order_by = value1, n = 5) %>% 
        mutate(chave1 = fct_reorder(.f = key1, .x = value2, .desc = FALSE))

   } 
        
}

But the second way I will need to copy and paste code, it's not good.

CodePudding user response:

Functions are objects in R, so you could simply assign the right function to a variable and call it later:

generates_data_graph <- function(data, positive = FALSE) { 
  slice_fn <- if (positive) slice_max else slice_min
  data_graph <- data %>%
    slice_fn(order_by = value1, n = 5) %>% 
    mutate(chave1 = fct_reorder(.f = key1, .x = value2, .desc = TRUE)
}
  • Related