假设我们有公司的支出数据,我们有不同项目的支出价值。我们如何采取样本,使样本中的支出总和占原始总支出的一定比例(比如说80%)(人口数据)?请帮忙!
答案 0 :(得分:0)
为再现性设置种子:
set.seed(12345)
创建一些样本数据,包含100个项目:
dat <- data.frame(proj = 1:100,
exp = sample(100:1000, 100, replace = TRUE))
totalexp <- sum(dat$exp)
随机排序数据
ord <- sample(1:nrow(dat),nrow(dat))
dat <- dat[ord,]
添加每个项目的总支出百分比:
dat$exp.prop <- dat$exp/totalexp
计算这些比例的累计总和:
dat$exp.cumsum <- cumsum(dat$exp.prop)
找到累积金额首先超过80%阈值的项目索引,并将项目样本作为该索引之前的所有项目:
proj.sample <- dat$proj[1:(which(dat$exp.cumsum>0.80)[1]-1)]
proj.sample
[1] 30 62 96 60 51 86 97 81 24 20 55 35 67 34 69 77 83 49 1 26 45
[22] 41 7 53 54 61 70 14 21 90 3 47 56 80 63 57 88 12 78 50 32 79
[43] 13 36 9 85 76 27 48 19 42 28 39 17 10 65 31 98 64 25 100 92 33
[64] 44 73 18 87 6 71 58 40 38 72 68 46 43 95 22