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

如何智能计算DataFrame行和并避免报错?含两类场景方案

先给出可复现的原始数据定义:

library(dplyr)

ori_df <- data.frame(values = 1:10) %>% t() %>% as.data.frame()
colnames(ori_df) <- LETTERS[1:10]

map_list <- list('group_a' = c('A','D','E'),'group_b' = c('G','H','Z'))

问题1:修复group_b求和的报错问题

原代码因Z列不存在触发报错,核心思路是只对数据框中实际存在的列求和,两种实现方式:

方式1:用rowSums + select + intersect

group_df <- ori_df %>% 
  mutate(
    group_a = A + D + E,
    group_b = rowSums(select(., intersect(c('G','H','Z'), colnames(.))))
  )

方式2:用rowwise + c_across

group_df <- ori_df %>% 
  rowwise() %>%
  mutate(
    group_a = A + D + E,
    group_b = sum(c_across(all_of(intersect(c('G','H','Z'), colnames(.)))))
  ) %>%
  ungroup()

两种方式都会自动忽略不存在的Z列,计算G+H的和且不会报错。


问题2:根据map_list批量生成分组列

要批量处理map_list中的所有分组,同时自动过滤不存在的列,推荐两种高效实现:

方式1:用purrr::map_dfc + bind_cols

library(purrr)

group_df <- ori_df %>%
  bind_cols(
    map_dfc(map_list, ~ rowSums(select(ori_df, intersect(.x, colnames(ori_df)))))
  )

方式2:用dplyr的非标准求值(!!!)

group_df <- ori_df %>%
  mutate(
    !!!map(map_list, ~ rowSums(select(., intersect(.x, colnames(.)))))
  )

这两种方式都会生成group_a(A+D+E)和group_b(G+H)列,全程不会因Z列不存在触发报错。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 01:29:58