R语言求解符合预设标准的四类特征剖面组合 用于分层抽样配置
问题解决方案
你遇到的是多维度分层样本的配额分配问题,暴力枚举所有可能性的方案时间和空间复杂度都极高,完全不可行,推荐以下两种可落地的实现方式:
方案1:整数规划求解(推荐,高效稳定)
该问题本质是带约束的整数规划问题,只需通过lpSolve包求解即可,无需枚举任何组合,毫秒级即可得到结果。
实现代码
# 安装依赖包(首次运行执行) install.packages("lpSolve") library(lpSolve) # 1. 生成所有24种特征剖面 profiles <- expand.grid( 性别 = c("Female", "Male"), 年龄 = c("Young", "Middle-aged", "Old"), 地域 = c("Urban", "Rural"), 教育程度 = c("Lower", "Higher") ) n_profiles <- nrow(profiles) # 2. 构造约束矩阵 const_mat <- rbind( # 性别约束 as.integer(profiles$性别 == "Female"), as.integer(profiles$性别 == "Male"), # 年龄约束 as.integer(profiles$年龄 == "Young"), as.integer(profiles$年龄 == "Middle-aged"), as.integer(profiles$年龄 == "Old"), # 地域约束 as.integer(profiles$地域 == "Urban"), as.integer(profiles$地域 == "Rural"), # 教育程度约束 as.integer(profiles$教育程度 == "Lower"), as.integer(profiles$教育程度 == "Higher") ) # 约束目标值 const_rhs <- c(13, 12, 7, 8, 10, 15, 10, 20, 5) # 所有约束为等于关系 const_dir <- rep("=", length(const_rhs)) # 目标函数(由于只需要满足约束,随便设置即可,这里设为全1求最小和) obj <- rep(1, n_profiles) # 3. 求解整数规划 result <- lp( direction = "min", objective.in = obj, const.mat = const_mat, const.dir = const_dir, const.rhs = const_rhs, all.int = TRUE ) # 4. 提取结果 profiles$抽样数 <- result$solution # 查看有抽样的剖面 head(profiles[profiles$抽样数 > 0, ])
结果校验
你可以通过以下代码验证结果是否符合要求:
sum(profiles$抽样数) # 总样本量应为25 sum(profiles$抽样数[profiles$性别 == "Female"]) # 应为13 sum(profiles$抽样数[profiles$年龄 == "Old"]) # 应为10 sum(profiles$抽样数[profiles$教育程度 == "Higher"]) # 应为5
方案2:迭代调整法(无需第三方包)
如果不想安装额外的规划包,可以通过简单的迭代微调得到结果:
- 第一步:计算每个特征剖面的期望抽样数 = 总样本量 * 性别占比 * 年龄占比 * 地域占比 * 教育占比,对结果四舍五入得到初始整数配额
- 第二步:计算各维度的配额偏差,每次调整偏差最大的剖面的抽样数(要么加1要么减1)
- 第三步:重复第二步直到所有维度的偏差都为0
该方法同样不需要枚举所有组合,迭代几十次即可得到符合要求的结果。
内容的提问来源于stack exchange,提问作者CNiessen
相关产品推荐
相关产品推荐

