r - 从多个因子列生成虚拟矩阵

标签 r dummy-variable

我已经在网上搜索过,没有找到答案。我有一个包含多列的大 data.frame。每列都是一个因子变量。

我想转换 data.frame,使因子变量的每个可能值都是一个变量,如果变量存在于因子列中则包含“1”,否则包含“0”。

这是我的意思的一个例子。

labels <- c("1", "2", "3", "4", "5", "6", "7") 

#create data frame (note, not all factor levels have to be in the columns,
#NA values are possible)
input <- data.frame(ID = c(1, 2, 3), 
Cat1 = factor(c( 4, 1, 1), levels = labels), 
Cat2 = factor(c(2, NA, 4), levels = labels),
Cat3 = factor(c(7, NA, NA), levels = labels))

#the seven factor levels now are the variables of the data.frame
desired_output <- data.frame(ID = c(1, 2, 3),
Dummy1 = c(0, 1, 1),
Dummy2 = c(1, 0, 0),
Dummy3 = c(0, 0, 0),
Dummy4 = c(1, 0, 1),
Dummy5 = c(0, 0, 0),
Dummy6 = c(0, 0, 0),
Dummy7 = c(1, 0, 0))

input
ID Cat1 Cat2 Cat3
1    4    2    7
2    1 <NA> <NA>
3    1    4 <NA>

desired_output
ID Dummy1 Dummy2 Dummy3 Dummy4 Dummy5 Dummy6 Dummy7
1      0      1      0      1      0      0      1
2      1      0      0      0      0      0      0
3      1      0      0      1      0      0      0

我的实际 data.frame 有 3000 多行和 100 多个级别的因素。 我希望你能帮助我将输入转换为所需的输出。

问候语 嘘

最佳答案

几个方法,重复 Gregor 和 Aaron 的回答。

来自亚伦的。 factorsAsStrings=FALSE 在使用 dcast

时保留因子变量因此所有标签
library(reshape2)
dcast(melt(input, id="ID", factorsAsStrings=FALSE), ID ~ value, drop=FALSE) 
  ID 1 2 3 4 5 6 7 NA
1  1 0 1 0 1 0 0 1  0
2  2 1 0 0 0 0 0 0  2
3  3 1 0 0 1 0 0 0  1

然后你只需要删除最后一列。

来自格雷戈尔的

na.replace <- function(x) replace(x, is.na(x), 0)
options(na.action='na.pass') # this keeps the NA's which are then converted to zero
Reduce("+", lapply(input[-1], function(x) na.replace(model.matrix(~ 0 + x))))
  x1 x2 x3 x4 x5 x6 x7
1  0  1  0  1  0  0  1
2  1  0  0  0  0  0  0
3  1  0  0  1  0  0  0

然后你只需要cbindID

关于r - 从多个因子列生成虚拟矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46773808/

相关文章:

r - 使用 aes_string 时 ggplot2 中两个 geom_point() 的颜色

pandas - 通过分组创建虚拟变量

python - 将数据框列字符串值转换为虚拟变量列

python - 根据 pandas 中的标准创建虚拟变量

r - 在没有 for 循环的情况下标记连续的观察 block

r - 遍历列表时获取列表的元素编号

r - 如何在保持字母顺序的情况下输出图形

r - 以分组观察中的重复为条件的虚拟变量

python - 虚拟变量水平不存在于未见数据中

r - 当我拆分列表中的data.frame时,如何使输出更加优雅?