Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

One can transfer values to a dplyr function that is piped within an if{} statement in a function by using curly braces {} to enclose the dplyr code and then pass the values using the . operator. For example:

my_function <- function(input_df, col_name, filter_value) {

  output_df <- if (is.numeric(input_df[[col_name]])) {

    input_df %>%
      filter({{col_name}} >= {{filter_value}})

  } else {

    input_df

  }

  return(output_df)

}

# Usage
my_data <- data.frame(names = c("Alice", "Bob", "Charlie"),
                      ages = c(25, 30, 35),
                      salaries = c(50000, 70000, 90000))

my_function(input_df = my_data, col_name = ages, filter_value = 30)

In this example, we pass the input data frame (my_data), column name (ages), and filter value (30) as arguments to the my_function. We use curly braces {} to enclose the dplyr code (filter function) and then use the . operator to pass the column name and filter value dynamically to the function. The output is a filtered data frame that only includes rows where the age is greater than or equal to 30.