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.
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
Asked: 2021-12-02 11:00:00 +0000
Seen: 8 times
Last updated: Mar 24 '23
What is the process of using the Multmerge() function in r to combine files in a directory?
Is it possible for two distinct useState functions to trigger changes simultaneously?
How can one use node to change an ogg file into an mp3 file?
How can a function pointer be transferred between different files in CUDA?
What does the error message "TypeError: e.endsWith is not a function" mean in Redoc?
What is the expected outcome of the math.floor function in terms of the return value?