0
$\begingroup$

This is my script for a decision tree in R:

    library(caret)
    library(rpart.plot)
    library(plyr)
    library(dplyr)
    
    data("iris")
    
    names(iris) = tolower(names(iris))
    
    table(iris$species)
    suppressMessages(library(caret))
    
    index = createDataPartition(y=iris$species, p=0.7, list=FALSE)
    
    train = iris[index,]
    test = iris[-index,]
    
    trainctrl <- trainControl(method = "cv", number = 5, verboseIter = FALSE)

dt.model <- train(species~., data=train, method = "rpart", 
                  tuneLength = 10,
                  preProcess = c("center", "scale"),
                  trControl = trainctrl,
                  metric="Kappa")

dt.predict <-predict(dt.model, test)
confusionMatrix(dt.predict, test$species)

How can I make the tree drawing with nodes?

$\endgroup$

1 Answer 1

2
$\begingroup$

You can use the built-in R plot function to get a simple drawing of your decision tree using the finalModel attribute:

plot(dt.model$finalModel)
text(dt.model$finalModel)

enter image description here

In addition, you can also use the rattle package to get a more visually appealing drawing of the decision tree:

enter image description here

$\endgroup$
2
  • $\begingroup$ Ok thanks, but I have this error when I run the code with my database: > plot(dt.model$finalModel) Error in plot.new() : figure margins too large > text(dt.model$finalModel) Error in rpartco(x) : no information available on parameters from previous call to plot() $\endgroup$
    – Inuraghe
    Dec 13, 2021 at 13:15
  • $\begingroup$ is there another way to know which characteristics the model considers more important? $\endgroup$
    – Inuraghe
    Dec 13, 2021 at 13:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.