Ask Your Question
0

How can one transfer values to a dplyr function that is piped within an if{} statement in a function?

asked 2021-12-02 11:00:00 +0000

ladyg gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2023-03-24 21:00:00 +0000

qstack gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2021-12-02 11:00:00 +0000

Seen: 8 times

Last updated: Mar 24 '23