请求:在R中创建自定义dplyr数据转换函数及学习资源
Absolutely, turning that repetitive code into a reusable function is a great idea—it’ll save you tons of time when working with different variables or datasets. Here’s a polished, flexible function using dplyr that does exactly what you need, plus some extra touches like handling missing values and clean formatting:
library(dplyr) calculate_stacked_percentages <- function(df, x_var, y_var) { # Generate percentage data for stacked bar charts df %>% # Keep only the relevant variables select({{x_var}}, {{y_var}}) %>% # Remove rows with missing values (optional but recommended) drop_na() %>% # Count occurrences of each x-y combination group_by({{x_var}}, {{y_var}}) %>% count(name = "n") %>% # Calculate percentage within each x group group_by({{x_var}}) %>% mutate(percentage = round(n / sum(n) * 100, 1)) %>% # Clean up grouping and sort for readability ungroup() %>% arrange({{x_var}}, {{y_var}}) }
How to Use It
Let’s test it with the mtcars dataset to see how it works—say we want percentages of gear types within each cyl category:
# Example usage stacked_data <- calculate_stacked_percentages(mtcars, cyl, gear) # View the result stacked_data
This will give you a dataframe with columns for your x variable, y variable, raw count (n), and percentage of each y category within its x group—perfect for feeding into a stacked bar chart (like with ggplot2).
Learning Resources for R Functions & dplyr
Since you asked about learning these tools, here are some solid, accessible resources you can use without leaving R:
- R Functions Basics: Type
?functionin your console to pull up the official R documentation on function syntax and structure. For hands-on practice, start by writing small functions (like one that calculates mean or filters data) and gradually build complexity. - dplyr Core Skills: Run
vignette("dplyr")to access the official dplyr getting-started guide—it walks you through all the key verbs (select, group_by, mutate, etc.) with clear examples. - Tidy Evaluation (for functions like this): If you want to understand how the
{{ }}syntax works, check outvignette("programming", package = "dplyr")—it explains how to write functions that work seamlessly with dplyr’s pipe-based workflow. - Practice Datasets: Use built-in datasets like
mtcars,iris, orgapminder(install it withinstall.packages("gapminder")) to experiment with functions and dplyr operations without needing external data.
内容的提问来源于stack exchange,提问作者Benjamin Telkamp

