dplyr准引用场景中调用stats(b)找不到列b,不改函数的最简解法
The error pops up because when you call stats(b) directly inside summarize, R tries to look for b in your global environment instead of within each grouped subset of your dataframe. The stats function expects a vector input, but b only exists as a column in your grouped data, not as a standalone global object.
Here are two straightforward solutions that don’t require modifying the stats function, optimized for your R 3.4.3 and dplyr 0.7.2 setup:
Solution 1: Use do() to work with grouped subsets
The do() function in dplyr lets you handle each group as an independent dataframe. You can access the b column of each group using .$b, pass it to stats, then convert the resulting list to a dataframe so do() can combine results across all groups:
df %>% group_by(a) %>% do(as.data.frame(stats(.$b)))
This will output the exact same result as your initial working summarize call:
| a | mn | md |
|---|---|---|
| 10 | 4.333333 | 2 |
| 20 | 3.000000 | 3 |
Solution 2: Use tidy evaluation to delay expression evaluation
Since dplyr 0.7 relies on rlang for tidy evaluation, you can capture the call to stats(b) and evaluate it within the grouped context. This keeps your workflow aligned with your original attempt to use !!! to splice the list results:
First, ensure rlang is loaded (it’s a required dependency of dplyr 0.7, so it should already be installed):
library(rlang)
Then use quo() to capture the expression, eval_tidy() to evaluate it inside each group, and !!! to splice the resulting list into the summarize arguments:
df %>% group_by(a) %>% summarize(!!! eval_tidy(quo(stats(b))))
This will produce the same output as the first solution.
内容的提问来源于stack exchange,提问作者scbagley

