在R中将分类列转换为多个二进制列

在R中将分类列转换为多个二进制列,r,R,我试图将一个包含分类数据的列(“a”、“B”或“C”)转换为3列,其中1,0,0将是“a”;0,1,0表示“B”,等等 我在网上找到了这段代码: flags = data.frame(Reduce(cbind, lapply(levels(d$purpose), function(x){(d$purpose == x)*1}) )) names(flags) = levels(d$purpose) d = cbind(d, flags) # Include the new colu

我试图将一个包含分类数据的列(“a”、“B”或“C”)转换为3列,其中1,0,0将是“a”;0,1,0表示“B”,等等

我在网上找到了这段代码:

flags = data.frame(Reduce(cbind, 
     lapply(levels(d$purpose), function(x){(d$purpose == x)*1})
))
names(flags) = levels(d$purpose)
d = cbind(d, flags)

# Include the new columns as input variables
levelnames = paste(names(flags), collapse = " + ")
neuralnet(paste("output ~ ", levelnames), d)

但我对R很陌生。有人能分析一下这个看起来很复杂的代码在做什么吗

编辑:

实施@nongkrong的建议我遇到了一个问题:

CSV:

R:

它适用于1列,但缺少X2D和X3Q。你知道为什么吗?

@nongkrong是对的——读一下
?公式
,你会发现大多数接受
公式
s作为输入的函数(例如
lm
glm
,等等)会自动将分类变量(存储为
因子
字符
s)转换为虚拟变量;通过在公式中指定
as.factor(var)
,可以强制非
factor
数值变量执行此操作


也就是说,我遇到过这样的情况,即手工创建这些指标是很方便的——例如,一个带有种族变量的数据集,在我认为不需要这些代码的情况下,您可以简单地使用
model.matrix(~purpose-1,data=d)
,但它所做的只是将factor变量扩展为一组虚拟列。每个虚拟列对应于原始因子的一个级别,并且该因子在originalAwesome中的位置为1,谢谢!我得到了这一点,可以很好地处理1列,但在多列中得到了奇怪的结果(请参见我对op的编辑)。我想这是因为
-1
,尝试删除它,看看会得到什么(尽管我原本预计
X1A
也会被删除…)它删除了一个截取列。现在,我通过一次做一列并使用cbind组合它们来解决这个问题。输出是这样的,因为这些虚拟列将您的因子的不同组合与基本情况截距进行对比(截距是使用
-1
从模型中删除的)。我不知道如何将这些专栏也包括在内,sadly@Michael.How假设我有多个列,每列中有多个因子,我可以为每列重复代码吗?我写了下面的代码,但它不工作,伪数据
df
fact1@user7462639我建议你问一个新问题,确保引用这个问题,并包括你迄今为止的尝试。正如我在回答中所建议的,你可能不想自己做这件事;另请参见
model.matrix
函数
X1,X2,X3
A,D,Q
B,E,R
C,F,S
B,G,T
C,H,U
A,D,Q
newData <- read.csv("new.csv")
newerData <- model.matrix(~ X1 + X2 + X3 -1, data=newData)
newerData
  X1A X1B X1C X2E X2F X2G X2H X3R X3S X3T X3U
1   1   0   0   0   0   0   0   0   0   0   0
2   0   1   0   1   0   0   0   1   0   0   0
3   0   0   1   0   1   0   0   0   1   0   0
4   0   1   0   0   0   1   0   0   0   1   0
5   0   0   1   0   0   0   1   0   0   0   1
6   1   0   0   0   0   0   0   0   0   0   0
flags = data.frame(Reduce(cbind, 
     lapply(levels(d$purpose), function(x){(d$purpose == x)*1})
))
#This line simply puts column names on each of the indicator variables
#  Note that you can replace the RHS of this line with whatever 
#  naming convention you want for the levels--a common approach might
#  be to specify paste0(levels(d$purpose),"_flag"), e.g.
names(flags) = levels(d$purpose)
#this line adds all the indicator variables to the original 
#  data.frame
d = cbind(d, flags)
#this creates a string of the form "level1 + level2 + ... + leveln"
levelnames = paste(names(flags), collapse = " + ")
#finally we create a formula of the form y~x+d1+d2+d3
#  where each of the d* is a dummy for a level of the categorical variable
neuralnet(paste("output ~ ", levelnames), d)
library(data.table)
setDT(d)
l = levels(purpose)
d[ , (l) := lapply(l, function(x) as.integer(purpose == x))]
d[ , neuralnet(paste0("output~", paste0(l, collapse = "+"))]