[英]How to apply weights – proportion of survey responses by different groups
我一直在應用權重方面遇到麻煩,所以這對你們所有人來說可能很容易。
我有調查數據,其中列出了每個觀察的權重。 我也有列標識 demo1、demo2 和年齡組以及每個問題的簡單數字響應與相應的列。 我想要做的是找到我的演示變量的比例,這些變量根據問題選擇了某些答案。 我可以使用以下代碼做到這一點:
data %>%
group_by(question1, demo1) %>%
summarise(count = n()) %>%
group_by(demo1) %>%
mutate(proportion = count/sum(count))
但是,我不知道如何准確應用相應的權重,這些權重位於不同的列(“權重”)中,有助於分析結果反映一般人群的人口統計數據。
謝謝你。
好吧,你沒有向我們展示你的詳細信息,所以我會有點猜測你的期望。 請參閱下面的示例。
library(tidyverse)
library(weights)
n=100
df = tibble(
question = rep(1:4, n),
demo1 = rep(c("dem1", "dem2"), each=length(question)/2),
demo2 = rep(c("dem1", "dem2", "dem3", "dem4"), each=length(question)/4),
weight = sample(c(1,3,5,8), length(question), replace = TRUE)
)
fweight1 = function(data) tibble(
prop = wpct(data$demo1, data$weight),
demo1 = wpct(data$demo1, data$weight) %>% names())
df %>% group_by(question) %>%
nest() %>%
mutate(prop1 = map(data, ~fweight1(.x))) %>%
unnest(prop1)
輸出
# A tibble: 8 x 4
# Groups: question [4]
question data prop demo1
<int> <list> <dbl> <chr>
1 1 <tibble [100 x 3]> 0.480 dem1
2 1 <tibble [100 x 3]> 0.520 dem2
3 2 <tibble [100 x 3]> 0.521 dem1
4 2 <tibble [100 x 3]> 0.479 dem2
5 3 <tibble [100 x 3]> 0.522 dem1
6 3 <tibble [100 x 3]> 0.478 dem2
7 4 <tibble [100 x 3]> 0.568 dem1
8 4 <tibble [100 x 3]> 0.432 dem2
現在同樣適用於demo2
fweight2 = function(data) tibble(
prop = wpct(data$demo2, data$weight),
demo2 = wpct(data$demo2, data$weight) %>% names())
df %>% group_by(question) %>%
nest() %>%
mutate(prop2 = map(data, ~fweight2(.x))) %>%
unnest(prop2)
輸出
# A tibble: 16 x 4
# Groups: question [4]
question data prop demo2
<int> <list> <dbl> <chr>
1 1 <tibble [100 x 3]> 0.259 dem1
2 1 <tibble [100 x 3]> 0.221 dem2
3 1 <tibble [100 x 3]> 0.249 dem3
4 1 <tibble [100 x 3]> 0.270 dem4
5 2 <tibble [100 x 3]> 0.272 dem1
6 2 <tibble [100 x 3]> 0.249 dem2
7 2 <tibble [100 x 3]> 0.216 dem3
8 2 <tibble [100 x 3]> 0.263 dem4
9 3 <tibble [100 x 3]> 0.244 dem1
10 3 <tibble [100 x 3]> 0.278 dem2
11 3 <tibble [100 x 3]> 0.211 dem3
12 3 <tibble [100 x 3]> 0.267 dem4
13 4 <tibble [100 x 3]> 0.271 dem1
14 4 <tibble [100 x 3]> 0.297 dem2
15 4 <tibble [100 x 3]> 0.203 dem3
16 4 <tibble [100 x 3]> 0.229 dem4
我使用了weights
包中的wpct
函數來計算考慮權重的比例。
請確認這是否是您的目標。 或者,使用dput
函數與我們共享您的一些數據。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.