首页 > 解决方案 > 如何从 R 中的给定答案创建一组虚拟变量?

问题描述

我真的很纠结这个问题。我有一个数据集:

example = data.frame(age = c(34,19,44,22,34,12,54,63,23),
                       wash.hands = c("Before eating","Before eating, on public transportation","Before eating, After eating",
                                      "After eating","on public transportation, when I get home","Before eating",
                                      "When I get home","When I get home, Before eating","on public transportation"),
                     stringsAsFactors = F
                       )

看起来像这样:

# age                                wash.hands
#  34                             Before eating
#  19   Before eating, on public transportation
#  44               Before eating, After eating
#  22                              After eating
#  34 on public transportation, when I get home
#  12                             Before eating
#  54                           When I get home
#  63            When I get home, Before eating
#  23                  on public transportation

它包含受访者的年龄,以及他何时洗手。我想有一组 4 个虚拟变量(饭前、饭后、乘坐公共交通工具、回家时),如果受访者在特定场合洗手,则它们签名为“1”,否则为 0。我怎么做???任何帮助,将不胜感激!谢谢!:)

标签: rvariables

解决方案


可以使用psychfastDummies

library(psych)
dummy.code(example$wash.hands)

library(fastDummies)
dummy_cols(example$wash.hands)

推荐阅读