r - 如何从 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。我怎么做???任何帮助,将不胜感激!谢谢!:)
解决方案
可以使用psych
或fastDummies
library(psych)
dummy.code(example$wash.hands)
library(fastDummies)
dummy_cols(example$wash.hands)
推荐阅读
- android - @gorhom/react-native-bottom-sheet 不适用于 Android
- php - PHP从两个数组中添加值
- node.js - 使用 unlink() 删除后无法提供文件
- c# - Nest - 搜索路径
- javascript - Javascript ajax django 地理位置查询
- javascript - JavaScript显示复选框onclick但第一次不起作用
- azure - 有没有办法从 Azure 位置 REST API 只获取“有效”位置?
- python - 比较或比较两个熊猫列元素明智
- javascript - 使用数据库中的数据填充空网格列
- hadoop - 从 python 文件创建配置单元表并使用 spark-submit 运行它失败