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

如何向嵌套tibble的fun1_result列追加单个dbl类型新列?

在嵌套tibble的已有结果中追加新统计列

你之前用map_dbl的问题在于,它会把每个分组的计算结果转换成数值向量,直接替换掉原来的fun1_result嵌套tibble列,这显然不是你要的效果。我们需要的是在每个fun1_result的小tibble里新增一列result3,下面是两种可行的解决方案:

方法一:一次性生成包含所有统计量的嵌套结果

直接在分组嵌套后,同时计算三个统计量并合并成一个tibble,流程更简洁高效:

library(tidyverse)

fun1 = function(df){
  result1 = min(df[,"Sepal.Width"])/max(df["Sepal.Length"])
  result2 = min(df[,"Sepal.Length"])/max(df["Sepal.Length"])
  tibble(result1, result2)
}

fun2 = function(df){
  min(df[,"Sepal.Width"])/2
}

df1 = iris %>% 
  group_by(Species) %>% 
  nest() %>% 
  mutate(fun1_result = map(data, ~{
    # 先调用fun1得到基础结果
    base_res = fun1(.x)
    # 计算result3并追加为新列
    base_res %>% mutate(result3 = fun2(.x))
  }))

方法二:对已有的fun1_result追加列

如果已经生成了fun1_result列,可以用map2同时遍历fun1_result和data列,把fun2的结果加到每个嵌套tibble中:

df1 = iris %>% 
  group_by(Species) %>% 
  nest() %>% 
  mutate(fun1_result = map(data, ~fun1(.x))) %>%
  # 用map2同时处理嵌套结果和对应分组数据
  mutate(fun1_result = map2(fun1_result, data, ~{
    .x %>% mutate(result3 = fun2(.y))
  }))

你可以用unnest展开验证结果:

df1 %>% unnest(fun1_result)

此时会看到每个Species对应的三列统计量:result1、result2、result3。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 16:12:48