Vector와 미묘하게 용도가 다르다 싶어서 한번 정리를 해야겠다고 마음먹던 차에..
Factor 자료형에 관해서 발표할 일이 있어서 주말간 정리해본 자료를 공유합니다.

Factor는 linear modeling을 위해 특별히 고안된 자료형인데, Levels 덕분에 분석작업시에
명목변수별로 데이터를 볼 수 있다는 장점이 있습니다. 아래의 자료를 참고해주세요 :D



[다운로드]


Factor.pdf


*대단한 자료는 아니지만, 가져가실 때 출처 밝혀주시는 센스! 부탁드립니다.




[코드]


factor(c("no", "yes") )


factor(c("yes", "no", "yes"), levels = c("yes", "no"))


factor(c("yes", "no", "yes"), levels = c("yes", "no") , ordered = T)


x <- factor(c("yes", "no", "yes", "yeah"), levels = c("yes", "no", "yeah"), ordered = T , nmax = 2)

x


?factor


x <- factor(c("yes", "no", "yes", "yeah"), levels = c("yes", "no", "yeah") , ordered = T, exclude =  "yeah")

x


levels(x)[1:2] <- "yes"

levels(x)



addNA(x, ifany = FALSE)


?addNA


d <- c(rep(1,5), rep(2,6), rep(3,8), rep(4,6))

d









hsb2 <- read.csv("https://stats.idre.ucla.edu/stat/data/hsb2.csv")


## race 컬럼에 factor 미적용시

summary(lm(write ~ race, data = hsb2))


# 팩터 변수 생성 후 race 컬럼에 적용한 결과

hsb2$race.f <- factor(hsb2$race)

is.factor(hsb2$race.f)

hsb2$race.f[1:15]

summary(lm(write ~ race.f, data = hsb2))


## 팩터변수를 외부에서 생성하기 싫은 경우 내부에 사용도 가능

hsb2 <- read.csv("https://stats.idre.ucla.edu/stat/data/hsb2.csv")

summary(lm(write ~ factor(race), data = hsb2))



## 확인시켜주는 함수, is. 시리즈

is.factor(x)

is.ordered(x) 


## 아예 변환시켜주는, as. 시리즈

as.factor(x)

as.ordered(x)


## levels만 뽑아보고 싶어 levels(), levels 가 몇개야? nlevels()

levels(x)

nlevels(x)


## 이 팩터변수 정보좀 가져와~ table(), 팩터형 좀 해제 시켜봐, unclass()

table(x)

unclass(x)



 

[참고 서적]


1. R을 활용한 머신러닝 - 브레트 란츠

2. R Programming - Coursera (2017년 강의)


반응형
Posted by JoeSung
,