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

使用dplyr::mutate时组内遇NA导致计算全为NA的解决方法

处理分组内存在NA时的极化值计算问题

你需要按country-year分组计算polarization变量,但当前代码在组内存在NA时会导致整组结果为NA。以下是解决方案:

示例数据

aus96 <- data.frame(country = c("AU", "AU", "AU", "AU", "AU", 
                                "NL", "NL", "NL", "NL", "NL",
                                "AU", "AU", "AU", "AU", "AU", 
                                "NL", "NL", "NL", "NL", "NL"),
                    party = c("Social", "Labor", "Democrats", "Liberal", "National",
                              "Social", "Labor", "Democrats", "Liberal", "National",
                              "Social", "Labor", "Democrats", "Liberal", "National",
                              "Social", "Labor", "Democrats", "Liberal", "National"),
                    lr = c(3.84, 4.33, 4.69, 6.45, 6.5,
                           4.84, 3.33, 2.69, 3.45, 10.5,
                           3.84, 4.33, NA, 6.45, 46.5,
                           4.84, 3.33, 2.69, 3.45, 1.5),
                    share = c(1.7, 38.7, 6.7, 38.6, 8.2,
                              5.7, 20.7, 26.7, 8.6, 8.2,
                              4.7, 28.7, 0, 40.6, 9.2,
                              1.7, 28.7, 16.7, 9.6, 18.2),
                    year = c(1,1,1,1,1,
                             1,1,1,1,1,
                             2,2,2,2,2,
                             2,2,2,2,2))

当前问题代码

aus96 %>% group_by(country, year) %>% 
  mutate(polarization = sqrt(sum((((lr-sum(((lr * share)/sum(share))))/5)^2)*share)))

上述代码中,当组内存在NA(如AU年份2的Democrats行lr为NA)时,所有sum()函数都会返回NA,最终导致整组polarization为NA。

修改后的代码

核心是在所有sum()函数中添加na.rm = TRUE参数,忽略NA值进行计算:

aus96 %>% 
  group_by(country, year) %>% 
  mutate(
    polarization = sqrt(
      sum(
        (((lr - sum((lr * share)/sum(share, na.rm = TRUE), na.rm = TRUE))/5)^2) * share,
        na.rm = TRUE
      )
    )
  )

说明

  • 每个嵌套的sum()都需要添加na.rm = TRUE,确保无论哪一层计算遇到NA都能跳过,基于可用数据完成计算。
  • 修改后,AU年份2的所有观测(包括Democrats行)都会得到有效的polarization值,不会因单个NA导致整组结果失效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 22:43:01