2016-11-25 47 views
0

我試圖用rpart在R中創建一個decisiontree。我如何使用rpart創建一棵簡單的樹?

#rm(list = ls()) 
cat("\014") 

library("rpart") 
#data 
mf <- factor(c("m","m","f","f","m","f","m")) 
heights <- c(180, 175 , 160, 166, 185, 170, 190) 
x = data.frame(cbind(heights, mf)) 
#create tree 
fit <- rpart(mf ~ ., data = x, method = "anova") 

predicted <- predict(fit,character = 180) 

我預計「預測」給我一個「m」或「f」,但我得到的只是一個微不足道的數字。 爲了得到一封信,我需要改變什麼?

感謝

回答

0

我認爲問題是,你的例子是太小了,我談到了使3倍。此外,「anova」方法旨在預測類別的手段。 (你也需要扔掉教你使用data.frame(cbind(...))的書)我猜你想要這樣的東西。

mf <- factor(c("m","m","f","f","m","f","m")) 
heights <- c(180, 175 , 160, 166, 185, 170, 190) 
x = data.frame(heights=rep(heights,3), mf) 
rm(heights);rm(mf) 
fit <- rpart(mf ~ heights, data = x, method="class") 

(predicted <- predict(fit, data.frame(heights = c(160,190)))) 
    f m 
1 1 0 
2 0 1 

png(); plot(fit) 
par(xpd=NA) 
text(fit, use.n = TRUE);dev.off() 

enter image description here