R语言中实现类似SUMIFS的多条件求和并新增列求助
R语言实现方案
方法一:用dplyr包(代码直观易读,推荐新手)
如果还没装过dplyr,先安装加载:
install.packages("dplyr") library(dplyr)
分两步完成需求:先算出符合条件的分组求和结果,再匹配到acme_two上:
# 第一步:从acme_one中筛选符合条件的行,按product_id和tag_id分组求和 sum_result <- acme_one %>% filter(true_false == 'TRUE', in_out == 'in') %>% group_by(product_id, tag_id) %>% summarise(totals = sum(quantity, na.rm = TRUE), .groups = "drop") # 第二步:把求和结果左连接到acme_two,确保所有acme_two的行都保留,无匹配的设为0 acme_two <- acme_two %>% left_join(sum_result, by = c("product_id", "tag_id")) %>% mutate(totals = ifelse(is.na(totals), 0, totals))
方法二:用base R(无需额外装包)
如果不想安装新包,用基础R的函数也能实现:
# 筛选符合条件的行 filtered_data <- subset(acme_one, true_false == 'TRUE' & in_out == 'in') # 按product_id和tag_id分组求和 sum_result <- aggregate(quantity ~ product_id + tag_id, data = filtered_data, sum, na.rm = TRUE) names(sum_result)[3] <- "totals" # 左连接到acme_two,NA值替换为0 acme_two <- merge(acme_two, sum_result, by = c("product_id", "tag_id"), all.x = TRUE) acme_two$totals[is.na(acme_two$totals)] <- 0
关键说明
na.rm = TRUE:防止quantity列有缺失值时求和结果变成NA- 左连接逻辑:保证acme_two里的所有行都保留,哪怕某个product_id+tag_id组合没有符合条件的记录,totals也会设为0(如果不需要设0,可以去掉对应的替换代码)
- 两种方法都能高效处理数万行的数据,不用担心性能问题
内容的提问来源于stack exchange,提问作者user14288796
相关产品推荐
相关产品推荐

