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

R语言:如何基于比例关联分配两个数据表

按比例将DataFrame行分配到另一个DataFrame的解决方案

这需求太常见了!咱们用R的dplyr和基础函数就能轻松实现,下面一步步来:

步骤1:准备示例数据

先把你给出的示例数据用tibble(dplyr里的DataFrame格式)写出来:

library(dplyr)

# 构建a表并计算比例
a <- tibble(
  color = c("red", "blue", "green", "orange"),
  n = c(1000, 500, 300, 200)
) %>%
  mutate(proportion = n / sum(n))

# 构建b表
b <- tibble(
  record = c("a", "b", "c", "d", "e", "f", "g", "h", "i", "j")
)

步骤2:计算每个颜色应分配的行数

这里要注意一个细节:直接用比例乘以b的总行数可能会因为四舍五入导致总数和b的行数不匹配,所以我们先做基础分配,再调整差值:

total_records <- nrow(b)

# 先按比例取整分配基础行数
a <- a %>%
  mutate(num_records = floor(proportion * total_records))

# 计算需要补充的行数(如果有差值)
diff <- total_records - sum(a$num_records)

# 把差值分配给比例最大的前diff个颜色(保证总数匹配)
a <- a %>%
  arrange(desc(proportion)) %>%
  mutate(num_records = if_else(row_number() <= diff, num_records + 1, num_records)) %>%
  arrange(match(color, c("red", "blue", "green", "orange"))) # 还原原颜色顺序

步骤3:生成分配结果表c

用rep()函数根据计算好的行数重复每个颜色,然后和b表合并:

# 生成对应长度的颜色向量
color_assignments <- rep(a$color, times = a$num_records)

# 合并得到c表
c <- b %>%
  mutate(color = color_assignments)

运行完上面的代码,你得到的c表就是:

# A tibble: 10 × 2
   record color 
   <chr>  <chr> 
 1 a      red   
 2 b      red   
 3 c      red   
 4 d      red   
 5 e      red   
 6 f      blue  
 7 g      blue  
 8 h      green 
 9 i      green 
10 j      orange

完全符合你示例里的分配比例(red占50%→5行,blue25%→2行,green15%→2行,orange10%→1行)。

小提示

如果你的数据量很大,或者不需要严格的整数匹配,也可以简化步骤直接用round()计算行数:

color_assignments <- rep(a$color, times = round(a$proportion * total_records))
c <- b %>% mutate(color = color_assignments)

这种方式在比例对应的行数刚好是整数时非常好用,省去了差值调整的步骤。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 07:53:39