You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

dplyr准引用场景中调用stats(b)找不到列b,不改函数的最简解法

Solution to "object 'b' not found" Error in dplyr Summarize

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:

amnmd
104.3333332
203.0000003

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 04:30:32