我有一个由许多变量组成的全国调查,比如这个(为了简单起见,我省略了一些变量):
year id y.b sex income married pens weight
2002 1 1950 F 100000 1 0 1.12
2002 2 1943 M 55000 1 1 0.55
2004 1 1950 F 88000 1 1 1.1
2004 2 1943 M 66000 1 1 0.6
2006 3 1966 M 12000 0 1 0.23
2008 3 1966 M 24000 0 1 0.23
2008 4 1972 F 33000 1 0 0.66
2010 4 1972 F 35000 1 0 0.67
如果id是受访者,y.b是出生年份,结婚是假人(1个已婚,0个单身),如果个人投资于补充养老金表格,则笔是假人,价值为1;权重是调查权重。
考虑到最初的调查是从2002年到2014年的4万次观察(我过滤它以便只有个人出现不止一次)。我使用此命令创建一个调查对象:
d.s <- svydesign(ids=~1, data=df, weights=~weight)
现在df是加权的,我想找到例如女性的百分比或投资于补充养老金的已婚人士的百分比;我在R帮助和网上阅读了一个命令来获得百分比,但我找不到合适的。
答案 0 :(得分:2)
# same setup
library(survey)
df <- data.frame(sex = c('F', 'M', 'F', 'M', 'M', 'M', 'F', 'F'),
married = c(1,1,1,1,0,0,1,1),
pens = c(0, 1, 1, 1, 1, 1, 0, 0),
weight = c(1.12, 0.55, 1.1, 0.6, 0.23, 0.23, 0.66, 0.67))
d.s <- svydesign(ids=~1, data=df, weights=~weight)
# subset to women only then calculate the share with a pension
svymean( ~ pens , subset( d.s , sex == 'F' ) )
答案 1 :(得分:0)
我并不完全知道你想对weight
做些什么,但这里有一个非常简单的解决方案,用于dplyr
中有退休金的女性比例:
df <- data.frame(sex = c('F', 'M', 'F', 'M', 'M', 'M', 'F', 'F'),
married = c(1,1,1,1,0,0,1,1),
pens = c(0, 1, 1, 1, 1, 1, 0, 0),
weight = c(1.12, 0.55, 1.1, 0.6, 0.23, 0.23, 0.66, 0.67))
d.s <- svydesign(ids=~1, data=df, weights=~weight)
# data frame of women with a pension
women_with_pension <- d.s$variables %>%
filter(sex == 'F' & pens == 1)
# number of rows (i.e. number of women with a pension) in that df
n_women_with_pension <- nrow(women_with_pension)
# data frame of all women
all_women <- d.s$variables %>%
filter(sex == 'F')
# number of rows (i.e. number of women) in that df
n_women <- nrow(all_women)
# divide the number of women with a pension by the total number of women
proportion_women_with_pension <- n_women_with_pension/n_women
这将为您提供养老金妇女的基本比例。运用同样的逻辑来获得有养老金的已婚人士的百分比。
就weight
变量而言,你是否试图做某种加权比例?在这种情况下,您可以将每个班级(养老金和所有女性)中女性的weight
值相加,如下所示:
# data frame of women with a pension
women_with_pension <- d.s$variables %>%
filter(sex == 'F' & pens == 1) %>%
summarise(total_weight = sum(weight))
# number of rows (i.e. number of women with a pension) in that df
women_with_pension_weight = women_with_pension[[1]]
# data frame of all women
all_women <- d.s$variables %>%
filter(sex == 'F') %>%
summarise(total_weight = sum(weight))
# number of rows (i.e. number of women) in that df
all_women_weight <- all_women[[1]]
# divide the number of women with a pension by the total number of women
# 0.3098592 for this sample data
prop_weight_women_with_pension <- women_with_pension_weight/all_women_weight