簡體   English   中英

如何在R中創建虛擬變量?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM