9

因此,我的数据集包含 15 个变量,其中一个(性别)只有 2 个级别。我想将其用作虚拟变量,但级别为 1 和 2。我该怎么做?我想要 0 和 1 级,但我不知道如何在 R 中管理它!

4

3 回答 3

24

使用带有公式接口的大多数 R 建模工具,您无需创建虚拟变量,处理和解释公式的基础代码将为您完成此操作。如果您出于其他原因想要一个虚拟变量,那么有几种选择。最简单的(恕我直言)是使用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

于 2012-10-11T15:47:56.853 回答
9

泰这个

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),结果将与您在上面的示例中看到的相同。

于 2012-10-11T15:47:07.513 回答
1

正如上面许多人所建议的,把它变成因素。

如果您真的想对性别变量进行虚拟编码,请考虑这个

set.seed(100)
gender = rbinom(100,1,0.5)+1
gender_dummy = gender-1
于 2015-04-15T12:57:28.800 回答