如何在dplyr中无需波浪号或引号使用.dots参数运行代码
Solution: Use Tidy Evaluation for Bare Column Names
The error occurs because when you pass gender and pet without quotes or tildes, R tries to look for global objects with those names (which don’t exist) instead of treating them as column names in your dataframe. Since you want to wrap this logic into a custom function, the cleanest approach is to use tidy evaluation—the modern way to handle column references in dplyr—letting you pass bare column names directly.
Step 1: Create the Custom Function
library(dplyr) calculate_group_percentages <- function(data, ...) { data %>% group_by(...) %>% # Accepts bare column names via the `...` argument summarize(counts = n(), .groups = "drop_last") %>% # Preserves the first grouping level mutate(perc = (counts / sum(counts)) * 100) %>% arrange(desc(perc)) }
Step 2: Use the Function with Bare Column Names
# Your sample data dataframe <- as.data.frame(cbind( gender = c("male", "female", "female", "female", "male", "female", "male"), pet = c("dog", "cat", "dog", "cat", "cat", "cat", "dog") )) # Call the function with bare column names (no quotes/tildes needed!) calculate_group_percentages(dataframe, gender, pet)
Output
# A tibble: 4 × 4 # Groups: gender [2] gender pet counts perc <fct> <fct> <int> <dbl> 1 female cat 3 75.0 2 male dog 2 66.7 3 male cat 1 33.3 4 female dog 1 25.0
Why This Works
- The
...in the function captures your bare column names as unevaluated expressions, so R doesn’t try to resolve them as global objects. group_by(...)uses tidy evaluation to map these expressions directly to columns in your input dataframe..groups = "drop_last"ensures we retain the first grouping level (gender) after summarizing, matching your original code’s behavior where percentages are calculated per gender group.
Note: The group_by_() syntax you used is deprecated in newer dplyr versions, so this modern approach is more maintainable and aligns with current best practices.
内容的提问来源于stack exchange,提问作者Indrajeet Patil
相关产品推荐
相关产品推荐

