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

使用map_dbl处理嵌套数据框时无法正确访问dim列的报错问题

问题原因

你使用nest_by()生成的是**行向分组(rowwise)**的 tibble 对象,此时直接对data列使用map_dbl遍历会受分组属性影响,导致子数据框的列读取异常,触发dim列不存在的报错。

解决方案

有两种可行的修正方式,任选其一即可:

方式1:保留nest_by(),直接行向调用函数(更简洁)

nest_by()本身已经开启了行分组,不需要额外用map_dbl遍历,直接在mutate中调用计算函数即可。
修正后代码:

behaviors_distance <- behaviors %>% 
                      nest_by(term) %>% 
                      mutate(distance = calc_distance_from_beh(data))

方式2:取消行分组后再使用map_dbl

如果需要保留map_dbl的写法,可以在nest_by()后调用ungroup()取消行向分组,再执行遍历:

behaviors_distance <- behaviors %>% 
                      nest_by(term) %>% 
                      ungroup() %>%
                      mutate(distance = map_dbl(data, calc_distance_from_beh))

两种方式运行后都可以得到正确的距离计算结果:

# 输出结果示例
# A tibble: 2 × 3
# Rowwise:  term
  term                  data distance
  <chr> <list<tibble[,2]>>    <dbl>
1 abandon            [3 × 2]    27.2 
2 abet               [3 × 2]     3.95

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 03:06:04