使用调查包创建虚拟变量
Create dummy variable with survey package
我想使用调查包将变量转换为虚拟变量。
我有一个复杂的样本设计,定义如下:
library(survey)
prestratified_design <- svydesign(
id = ~ PSU ,
strata = ~ STRAT,
data = data,
weights = ~ weight ,
nest = TRUE)
数据集有一个教育变量,分为 8 个不同的类别:
# A tibble: 8 x 3
education n prop
<int> <int> <dbl>
1 1 2919 20.8
2 2 5551 39.5
3 3 447 3.18
4 4 484 3.45
5 5 3719 26.5
6 6 91 0.65
7 9 790 5.63
8 10 39 0.28
我想为类别 5 和 10 == 1 和其他 == 0 创建一个虚拟变量。
我知道我要用update函数,但是我不知道survey包里的if怎么用。
我试过:
prestratified_design <- update(
prestratified_design,
dummy_educ = as.numeric (education == 5 & education == 10)
但显然没有用。
谢谢!
如果类别数为两个,您可以通过 ifelse()
在 R 中创建虚拟变量。
df$dummy_educ = with(df, ifelse(education == 5 | education == 10, 1, 0))
如果类别更多,您可以使用 dplyr::case_when()
,如果您从因子变量创建虚拟变量,model.matrix()
速度快且最好。
为了让任何新变量都考虑到复杂设计,您不需要更新数据集(在您的示例中 data
),但您必须更新调查设计并添加新变量.您必须使用 survey::update()
函数。
按照您的示例,尝试使用以下代码:
prestratified_design <- update(prestratified_design,
dummy_educ = as.integer(education == 5 | education == 10))
祝你好运!
我想使用调查包将变量转换为虚拟变量。
我有一个复杂的样本设计,定义如下:
library(survey)
prestratified_design <- svydesign(
id = ~ PSU ,
strata = ~ STRAT,
data = data,
weights = ~ weight ,
nest = TRUE)
数据集有一个教育变量,分为 8 个不同的类别:
# A tibble: 8 x 3
education n prop
<int> <int> <dbl>
1 1 2919 20.8
2 2 5551 39.5
3 3 447 3.18
4 4 484 3.45
5 5 3719 26.5
6 6 91 0.65
7 9 790 5.63
8 10 39 0.28
我想为类别 5 和 10 == 1 和其他 == 0 创建一个虚拟变量。
我知道我要用update函数,但是我不知道survey包里的if怎么用。 我试过:
prestratified_design <- update(
prestratified_design,
dummy_educ = as.numeric (education == 5 & education == 10)
但显然没有用。
谢谢!
如果类别数为两个,您可以通过 ifelse()
在 R 中创建虚拟变量。
df$dummy_educ = with(df, ifelse(education == 5 | education == 10, 1, 0))
如果类别更多,您可以使用 dplyr::case_when()
,如果您从因子变量创建虚拟变量,model.matrix()
速度快且最好。
为了让任何新变量都考虑到复杂设计,您不需要更新数据集(在您的示例中 data
),但您必须更新调查设计并添加新变量.您必须使用 survey::update()
函数。
按照您的示例,尝试使用以下代码:
prestratified_design <- update(prestratified_design,
dummy_educ = as.integer(education == 5 | education == 10))
祝你好运!