[英]How do I make a dummy variable in R?
因此,我的数据集包含15个变量,其中一个(性别)只有2个级别。 我想将其用作虚拟变量,但级别为1和2。我该怎么做? 我想拥有0和1级,但是我不知道如何在R中进行管理!
使用R的大多数带有公式接口的建模工具,您无需创建虚拟变量,处理和解释公式的基础代码将为您完成此任务。 如果由于其他原因想要虚拟变量,则有几种选择。 最简单的(IMHO)是使用model.matrix()
:
set.seed(1)
dat <- data.frame(sex = sample(c("male","female"), 10, replace = TRUE))
model.matrix( ~ sex - 1, data = dat)
这使:
> dummy <- model.matrix( ~ sex - 1, data = dat)
> dummy
sexfemale sexmale
1 0 1
2 0 1
3 1 0
4 1 0
5 0 1
6 1 0
7 1 0
8 1 0
9 1 0
10 0 1
attr(,"assign")
[1] 1 1
attr(,"contrasts")
attr(,"contrasts")$sex
[1] "contr.treatment"
> dummy[,1]
1 2 3 4 5 6 7 8 9 10
0 0 1 1 0 1 1 1 1 0
您可以将dummy
列中的任何一列用作数字虚拟变量。 选择要成为基于1
的级别的列。 dummy[,1]
选择1
代表女性类别, dummy[,2]
代表男性类别。
如果希望将其解释为分类对象,请将其强制转换为一个因素:
> factor(dummy[, 1])
1 2 3 4 5 6 7 8 9 10
0 0 1 1 0 1 1 1 1 0
Levels: 0 1
但这正在打破因素的目标; 又是什么0
?
这个
set.seed(001) # generating some data
sex <- factor(sample(1:2, 10, replace=TRUE)) # this is what you have
[1] 1 1 2 2 1 2 2 2 2 1
Levels: 1 2
sex<-factor(ifelse(as.numeric(sex)==2, 1,0)) # this is what you want
sex
[1] 0 0 1 1 0 1 1 1 1 0
Levels: 0 1
如果您希望标签为0 =男性和1 =女性,那么...
sex<-factor(ifelse(as.numeric(sex)==2, 1,0), labels=c('M', 'F'))
sex # this is what you want
[1] M M F F M F F F F M
Levels: M F
实际上,您不需要创建虚拟变量即可使用lm
估计模型,让我们看一下此示例:
set.seed(001) # Generating some data
N <- 100
x <- rnorm(N, 50, 20)
y <- 20 + 3.5*x + rnorm(N)
sex <- factor(sample(1:2, N, replace=TRUE))
# Estimating the linear model
lm(y ~ x + sex) # using the first category as the baseline (this means sex==1)
Call:
lm(formula = y ~ x + sex)
Coefficients:
(Intercept) x sex2
19.97815 3.49994 -0.02719
# renaming the categories and labelling them
sex<-factor(ifelse(as.numeric(sex)==2, 1,0), labels=c('M', 'F'))
lm(y ~ x + sex) # the same results, baseline is 'Male'
Call:
lm(formula = y ~ x + sex)
Coefficients:
(Intercept) x sexF
19.97815 3.49994 -0.02719
如您所见,R很好地处理了虚拟变量,您只需将它们作为factor
变量传递到公式中,R就会为您完成其余工作。
顺便说一下,无需将类别从c(2,1)更改为c(0,1),结果将与您在上面的示例中看到的相同。
正如以上许多建议所言,将其变成因素。
如果您真的想对性别变量进行虚拟编码,请考虑一下
set.seed(100)
gender = rbinom(100,1,0.5)+1
gender_dummy = gender-1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.