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

如何查看survey包中各观测值权重并生成带权重列的data.table?

提取survey加权后的观测权重并生成带权重的data.table

提取权重向量

survey包提供了weights()函数,直接从加权后的设计对象中提取每个观测的权重:

# 从rake加权对象中提取权重
weights_vec <- weights(data.svy.rake)

合并权重到原数据并转为data.table

加载data.table包后,把原数据转成data.table格式,再新增weight列:

library(data.table)
# 转换原数据为data.table并添加权重列
data_dt <- as.data.table(data)
data_dt[, weight := weights_vec]

完整可运行代码

# 加载依赖包
library(survey)
library(data.table)

# 原始数据生成
set.seed(12345)
preYear = c(0:100)
preYear = sample(preYear, 100, replace = TRUE)
income = c(0:100000)
income = sample(income, 100, replace = TRUE)
gender = c("Male", "Female")
gender = sample(gender, 100, replace = TRUE)
gender = as.numeric(factor(gender))
ethnicity = c("White", "African_American", "Mixed_Ethnicity", "Other_Ethnicity")
ethnicity = sample(ethnicity, 100, replace = TRUE)
ethnicity = as.numeric(factor(ethnicity))
postYear = preYear + 10
data = cbind(preYear, income, gender, ethnicity, postYear)
data = as.data.frame(data)

# rake加权流程
data.svy.unweighted <- svydesign(ids=~1, data=data)
gender.dist <- data.frame(gender = c("1", "2"),
                          Freq = nrow(data) * c(0.45, 0.55))
data.svy.rake <- rake(design = data.svy.unweighted,
                      sample.margins = list(~gender),
                      population.margins = list(gender.dist))

# 提取权重并生成目标data.table
weights_vec <- weights(data.svy.rake)
data_dt <- as.data.table(data)
data_dt[, weight := weights_vec]

# 查看前几行结果
head(data_dt)

可选:验证权重效果

可以检查加权后的性别分布是否符合预设的45%/55%比例:

# 计算加权后的性别占比
data_dt[, .(male_prop = sum(weight[gender==1])/sum(weight),
            female_prop = sum(weight[gender==2])/sum(weight))]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 12:35:19