You need to enable JavaScript to run this app. R语言将未知loc的计数值按分组占比分配到A/B分组的实现方法
优惠活动
大模型
产品
解决方案
定价
更多

R语言将未知loc的计数值按分组占比分配到A/B分组的实现方法

需求说明

针对给定的长表结构数据,按以下规则处理:

  • 对每个id分组,将loc为?的未知行的count1、count2数值,按同id下A、B对应count列的占比分摊到A、B行中
  • 分摊完成后删除所有loc为?的行
  • 要求分摊后每个id下各count列的总和与原数据保持一致
示例数据
library(tidyverse)
x <- structure(list(id = c(1L, 1L, 1L, 2L, 2L, 2L), loc = c("A", "B", "?", "A", "B", "?"), count1 = c(10L, 20L, 50L, 5L, 22L, 10L), count2 = c(324L, 564L, 121L, 87L, 66L, 445L)), row.names = c(NA, -6L), class = c("tbl_df", "tbl", "data.frame"))
x
#> # A tibble: 6 x 4
#>      id loc   count1 count2
#>   <int> <chr>  <int>  <int>
#> 1     1 A         10    324
#> 2     1 B         20    564
#> 3     1 ?         50    121
#> 4     2 A          5     87
#> 5     2 B         22     66
#> 6     2 ?         10    445
预期输出
expected <- structure(list(id = c(1L, 1L, 2L, 2L), loc = c("A", "B", "A", "B"), count1 = c(26.67, 53.33, 6.85, 30.15), count2 = c(368.15, 640.85, 340.04, 257.96)), row.names = c(NA, -4L), class = c("tbl_df", "tbl", "data.frame"))

expected
#> # A tibble: 4 x 4
#>      id loc   count1 count2
#>   <int> <chr>  <dbl>  <dbl>
#> 1     1 A      26.7    368.
#> 2     1 B      53.3    641.
#> 3     2 A       6.85   340.
#> 4     2 B      30.2    258.

# 总计数值验证
x %>% group_by(id) %>% summarise(across(count1:count2, sum))
#> # A tibble: 2 x 3
#>      id count1 count2
#>   <int>  <int>  <int>
#> 1     1     80   1009
#> 2     2     37    598
expected %>% group_by(id) %>% summarise(across(count1:count2, sum))
#> # A tibble: 2 x 3
#>      id count1 count2
#>   <int>  <dbl>  <dbl>
#> 1     1     80   1009
#> 2     2     37    598
实现代码
library(tidyverse)

result <- x %>%
  group_by(id) %>%
  # 按id分组计算待分摊参数
  mutate(
    # 提取当前id下未知行的各count总和
    count1_unknown = sum(count1[loc == "?"]),
    count2_unknown = sum(count2[loc == "?"]),
    # 提取当前id下A+B行的各count总和
    count1_ab_sum = sum(count1[loc != "?"]),
    count2_ab_sum = sum(count2[loc != "?"]),
    # 按占比分摊数值到对应行
    count1 = count1 + count1_unknown * count1 / count1_ab_sum,
    count2 = count2 + count2_unknown * count2 / count2_ab_sum
  ) %>%
  # 过滤掉未知行,保留需要的列,四舍五入对齐预期结果
  filter(loc != "?") %>%
  select(id, loc, count1, count2) %>%
  mutate(across(count1:count2, ~round(.x, 2))) %>%
  ungroup()

# 查看结果
result

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.11 13:18:03