【R語言學習筆記】10. 將分類變量轉換為啞變量


 

setwd("/Users/shanshantong/Desktop/Skills/1.Tools/R/6.Datasets/")
housing.df <- read.csv("WestRoxbury.csv", header = TRUE)  # load data
table(housing.df$REMODEL)

  

 

 

Method1

# Option1: use dummies package
library(dummies) #load dummies package
housing.df <- dummy.data.frame(housing.df, sep = ".") 
#dummy.data.frame() -> create dummy variables for "Remodel"
#sep = "." -> separator b/w previous name and level
names(housing.df)

 

 

 

Method2

# Option 2: use model.matrix() to convert all categorical variables in the data frame into a set of dummy variables. 
# We must then turn the resulting data matrix back into a data frame for further work.
housing.df <- read.csv("WestRoxbury.csv", header = TRUE)  # load data

xtotal <- model.matrix(~ 0 + REMODEL, data = housing.df)
xtotal <- as.data.frame(xtotal)
t(t(names(xtotal)))  # check the names of the dummy variables

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM