R에서 의사결정나무 분석을 하려면 rpart 패키지가 필요하다. 다음 명령어로 패키지를 설치하자.
install.packages("rpart", dep=T)
먼저 rpart 패키지를 불러들인다.
library(rpart)
다음은 예제용 자료이다.
customer = read.table(stdin(),header=T,sep=",") District,HouseType,Income,PreviousCustomer,Outcome Suburban,Detached,High,No,Nothing Suburban,Detached,High,Responded,Nothing Rural,Detached,High,No,Responded Urban,Semi-detached,High,No,Responded Urban,Semi-detached,Low,No,Responded Urban,Semi-detached,Low,Responded,Nothing Rural,Semi-detached,Low,Responded,Responded Suburban,Terrace,High,No,Nothing Suburban,Semi-detached,Low,No,Responded Urban,Terrace,Low,No,Responded Suburban,Terrace,Low,Responded,Responded Rural,Terrace,High,Responded,Responded Rural,Detached,Low,No,Responded Urban,Terrace,High,Responded,Nothing
의사결정나무 분석은 rpart 함수를 사용한다. 기본적인 사용법은 lm 함수와 유사하다. 다음은 customer의 Outcome을 종속변수로 다른 변수들을 독립변수로 분석하는 예이다.
customer.tree1 = rpart(Outcome ~ . , data=customer)
customer.tree1을 쳐보면 다음과 같은 분석 결과를 볼 수 있다.
node), split, n, loss, yval, (yprob)
* denotes terminal node
1) root 14 5 Responded (0.3571429 0.6428571) *
분석 결과가 저렇게 단순한 이유는 자료가 14건 밖에 안되기 때문이다. rpart 함수는 최소한 한 가지(node)에 20건은 들어가도록 기본설정이 되어 있다. 그러면 이 기본설정을 바꾸어보자.
customer.tree2 = rpart(Outcome ~ . , data=customer, control=rpart.control(minsplit=1))
새로운 분석 결과는 다음과 같다.
1) root 14 5 Responded (0.3571429 0.6428571)
2) District=Suburban,Urban 10 5 Nothing (0.5000000 0.5000000)
4) Income=High 5 1 Nothing (0.8000000 0.2000000)
8) HouseType=Detached,Terrace 4 0 Nothing (1.0000000 0.0000000) *
9) HouseType=Semi-detached 1 0 Responded (0.0000000 1.0000000) *
5) Income=Low 5 1 Responded (0.2000000 0.8000000)
10) PreviousCustomer=Responded 2 1 Nothing (0.5000000 0.5000000)
20) District=Urban 1 0 Nothing (1.0000000 0.0000000) *
21) District=Suburban 1 0 Responded (0.0000000 1.0000000) *
11) PreviousCustomer=No 3 0 Responded (0.0000000 1.0000000) *
3) District=Rural 4 0 Responded (0.0000000 1.0000000) *
그래프로 그려보려면 다음과 같이 한다. plot은 나무 그림을 그리고 text는 라벨을 달아 준다. 각각의 옵션을 설명하면 compress이 T면 세로 폭을, uniform이 T면 가로폭을 좁혀준다. margin은 여백을 설정해준다. 여백이 0이면 라벨이 잘릴 수 있기 때문에 조금씩 설정해주도록 한다. text에서 use.n은 0/4와 같은 표시를 달아준다. 자세한 내용은 도움말을 참조. plot과 text는 실제로 plot.rpart와 plot.text를 호출하기 때문에 도움말도 해당 함수를 찾아봐야 한다.
plot(customer.tree2, compress=T,uniform=T,margin=0.1) text(customer.tree2, use.n=T, col='blue')
