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

使用purrr::map引用嵌套列时的分组Bootstrap计算报错问题

问题原因与解决方案

错误根源

你写的calc_mpg_mean函数是用来处理单个抽样拆分(rsplit对象)的,但boots列中的每个元素是bootstraps()生成的抽样集合(rset对象)——也就是包含1000个rsplit的表格。直接用map(boots, calc_mpg_mean)相当于把整个抽样集合传给了函数,analysis()自然会报错,因为它只接受单个rsplit。

修正代码

你需要在boots的基础上再嵌套一层map,遍历每个抽样集合里的split元素,再应用计算函数:

library(tidyverse)
library(tidymodels)    

# 原计算函数无需修改
calc_mpg_mean <- function(split){
  dat <- analysis(split) %>% pull(mpg)
  tibble(
    term = "mean",
    estimate = mean(dat),
    std.err = sd(dat)/sqrt(length(dat))
  )
}

# 修正后的完整流程
mtcars %>%
  group_by(cyl) %>%
  nest() %>%
  mutate(boots = map(data, ~bootstraps(.x, times = 1000, apparent = TRUE))) %>%
  # 遍历每个boot集合里的split,应用函数并合并结果
  mutate(mean_mpg = map(boots, ~map_dfr(.x$splits, calc_mpg_mean))) %>%
  # 可选:展开结果查看每组的所有bootstrap均值
  unnest(mean_mpg)

更简洁的tidymodels风格写法

如果你想用tidymodels的原生工具处理,可以用fit_resamples来自动处理bootstrap抽样的计算,代码更规范:

mtcars %>%
  group_by(cyl) %>%
  nest() %>%
  mutate(
    boots = map(data, ~bootstraps(.x, times = 1000, apparent = TRUE)),
    mean_mpg = map(boots, ~fit_resamples(
      mpg ~ 1, 
      model = linear_reg() %>% set_engine("lm"),
      resamples = .x,
      metrics = metric_set(mean)
    ) %>% collect_metrics())
  ) %>%
  unnest(mean_mpg)

内容的提问来源于stack exchange,提问作者Anthony W

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 17:01:35