Home > Enterprise >  How to make this function dynamic? R function
How to make this function dynamic? R function

Time:05-23

i have a function in R that generates a table graph picking data from a dataframe and every time i want to pass a different variable (column name from dataframe) i have to repeat the code. So sometimes it can be the variable and sometimes the variableb, other times the variablec... etc.

generates_table_variablea <- function(data) { ## how to pass the column = variablea here like this 
                                              ####### function(data, column = variablea) .. ???
  
  big_data <- data %>%
    group_by(a, b, c, d) %>% 
    mutate(total_categoria_abs = sum(abs(f))) %>%
    mutate(volume_negativo = if_else(variablea < 0, f, 0)) %>% 
    mutate(volume_positivo = if_else(variablea > 0, f, 0)) %>%
    mutate(total = sum(volume_positivo) - sum(volume_negativo)) %>% 
    mutate(e = if_else(variablea < 0, sum(variablea), 0)) %>% 
    ungroup() %>% 
    filter (variablea < 0) %>% 
    group_by(a, b, c, d) %>% 
    summarise(e = mean(e), vendas = sum(f*-1), frac_vendas = vendas*-1/mean(total_categoria_abs)) %>%
    arrange(e) %>% 
    ungroup() 
  
  
  big_data$frac_vendas <- round(big_data$frac_vendas, digits = 2)
  
  big_data$e <- round(big_data$e, digits = 0)
  
}

If I want to change this variable, I have to do the follow:

generates_table_variableb <- function(data) { ## HERE IT WILL BE function(data, column = variableb)...
  
  big_data <- data %>%
    group_by(a, b, c, d) %>% 
    mutate(total_categoria_abs = sum(abs(f))) %>%
    mutate(volume_negativo = if_else(variableb < 0, f, 0)) %>% #### HERE I NEED TO CHANGE ALWAYS TO VARIABLEA, VARIABLEB, VARIABLEC...
    mutate(volume_positivo = if_else(variableb > 0, f, 0)) %>%
    mutate(total = sum(volume_positivo) - sum(volume_negativo)) %>% 
    mutate(e = if_else(variablea < 0, sum(variableb), 0)) %>% 
    ungroup() %>% 
    filter (variableb < 0) %>% 
    group_by(a, b, c, d) %>% 
    summarise(e = mean(e), vendas = sum(f*-1), frac_vendas = vendas*-1/mean(total_categoria_abs)) %>%
    arrange(e) %>% 
    ungroup() 
  
  
  big_data$frac_vendas <- round(big_data$frac_vendas, digits = 2)
  
  big_data$e <- round(big_data$e, digits = 0)
  
} 

Having multiple functions doing the same thing is slowing down my code...

How could this be better? All that I want is to pass this column dynamically.

CodePudding user response:

This is one of the way

library(dplyr)
x <- data.frame(v1=1:3, v2=4:6)
f <- function(data, var1){
  x %>% select(!!var1)
}
f(x, quo(v1))

You can see more explanation in https://adv-r.hadley.nz/quasiquotation.html

  • Related