首页 > 解决方案 > 我可以将 pivot_longer() 与来自 srvyr 的调查设计对象一起使用吗?

问题描述

有没有办法使用pivot_longer()在 中生成的调查设计对象srvyr?我想制作一个显示一系列变量的多面图,因此我想将四个或五个人口统计变量放入一个长数据框中并绘制加权数据。

以下代码是可重现的,但确实安装了一个包。对此感到抱歉,这是我能想到的最好的重现我的问题的方法。使用未加权的数据很容易获得我需要的东西,但我不知道如何使用加权数据来做到这一点。

library(tidyverse)
library(srvyr)
#output of dput 
ces2019_web<-tibble::tribble(
  ~cps19_province, ~cps19_education, ~cps19_weight_general_all,
  "24",             "10",         0.681336402893066,
  "24",             "10",         0.681336402893066,
  "22",              "8",         0.650459408760071,
  "22",              "8",          0.88725334405899,
  "22",              "5",          1.65380775928497,
  "22",              "8",         0.650459408760071
)
# convert values to factor type
ces2019_web <- to_factor(ces2019_web)
#Make the survey design 
ces2019_web %>% 
  filter(!is.na(cps19_weight_general_all)) %>% 
  as_survey_design(., weight=cps19_weight_general_all)->des
#Look for two demographic variables similar to what I'm working with 
#Show the ideal end product but for unweighted data
ces2019_web %>% 
  as_factor() %>% 
  pivot_longer(., cols=c(1:2)) %>% 
  group_by(name, value) %>% 
  summarize(n=n()) %>% 
  mutate(pct=n/sum(n)) %>% 
  knitr::kable()
#Show with weighted data;
#Require a solution
des %>% 
  select(cps19_province, cps19_education) %>% 
  pivot_longer()

标签: rtidyversetidyr

解决方案


There are no plans to implement pivot_longer or pivot_wider (or other tidyr functions that change the dimensionality of a dataset) in srvyr because they change the dataset in ways that require altering the survey design that can't be automatically determined. You'll need to know how to specify the correct design with the new dataset.

I've always felt that you should pivot (and otherwise tidy) the dataset before converting it to a tbl_svy.


推荐阅读