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

基于特定值条件对成对列向量计算行求和(R语言)

问题:按条件配对列求和生成overall_total列

原始数据集

df <- structure(list(datA = c(1L, NA, 5L, 3L, 8L, NA), datA_total = c(20L, 
30L, 40L, 15L, 10L, NA), datB = c(5L, 5L, NA, 6L, 1L, NA), datB_total = c(80L, 
10L, 10L, 5L, 4L, NA), datC = c(NA, 4L, 1L, NA, 3L, NA), datC_total = c(NA, 
10L, 15L, NA, 20L, NA)), class = "data.frame", row.names = c(NA, 
-6L))

打印后结果:

#  datA datA_total datB datB_total datC datC_total
#1    1         20    5         80   NA         NA        
#2   NA         30    5         10    4         10         
#3    5         40   NA         10    1         15
#4    3         15    6          5   NA         NA  
#5    8         10    1          4    3         20
#6   NA         NA   NA         NA   NA         NA

需求

创建overall_total列,仅当类型列(datA/datB/datC)的值在1-5范围内时,将对应总计列(datA_total/datB_total/datC_total)的值纳入行求和;全NA的行求和为0。期望结果:

#  datA datA_total datB datB_total datC datC_total overall_total
#1    1         20    5         80   NA         NA           100
#2   NA         30    5         10    4         10            20
#3    5         40   NA         10    1         15            55 
#4    3         15    6          5   NA         NA            15
#5    8         10    1          4    3         20            24
#6   NA         NA   NA         NA   NA         NA             0

错误代码分析

你尝试的代码逻辑完全错误:

type_vars <- c("datA", "datB", "datC")
type_scores <- c("1", "2", "3", "4", "5")
type_visits <- c("datA_total", "datB_total", "datC_total")

df <- df %>%
       mutate(overall_total = rowSums(all_of(type_visits[type_vars %in% type_scores])))
  • type_vars是列名字符向量,type_scores是数字字符串,两者用%in%比较毫无意义,导致type_visits[type_vars %in% type_scores]是空向量,rowSums无法计算
  • 没有实现按行判断每个类型列的值是否符合条件,再对应取总计列求和的核心逻辑

正确解法

方法1:用rowwise+purrr批量处理配对列

适合列数较多的场景,扩展性强:

library(dplyr)
library(purrr)

# 定义类型列与总计列的配对关系
type_pairs <- list(
  c("datA", "datA_total"),
  c("datB", "datB_total"),
  c("datC", "datC_total")
)

df <- df %>%
  rowwise() %>%
  mutate(
    overall_total = sum(
      map_dbl(type_pairs, ~{
        # 取出当前行的类型列值和总计列值
        type_val <- pick(all_of(.x[1]))[[1]]
        total_val <- pick(all_of(.x[2]))[[1]]
        # 符合条件则取总计值,否则取0
        if (!is.na(type_val) && type_val %in% 1:5) total_val else 0
      }),
      na.rm = TRUE
    )
  ) %>%
  ungroup()

方法2:直接对每对列做条件判断(简洁直观)

适合列数较少的场景:

library(dplyr)

df <- df %>%
  mutate(
    overall_total = 
      # 对每对列分别判断,符合条件则加对应总计,否则加0
      (ifelse(between(datA, 1, 5) & !is.na(datA), datA_total, 0) +
       ifelse(between(datB, 1, 5) & !is.na(datB), datB_total, 0) +
       ifelse(between(datC, 1, 5) & !is.na(datC), datC_total, 0)) %>%
      # 把全NA的行结果替换为0
      replace_na(0)
  )

两种方法都能得到你期望的结果,其中方法2代码更简洁,方法1适合后续新增配对列的情况,只需在type_pairs里添加新的配对即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 01:00:59