how to make a discision tree in r

To create a decision tree in R, we can use the rpart package. Here is an example code that demonstrates how to do it:

main.r
# Load the rpart package
library(rpart)

# Load the iris dataset
data(iris)

# Build the decision tree model using rpart
model <- rpart(Species ~ ., data = iris, method = "class")

# Plot the decision tree
plot(model)
text(model)
230 chars
13 lines

In this code, we first load the rpart package and the iris dataset which is built-in R dataset. Then, we create a decision tree model using rpart() function with formula Species ~ . which uses all the other variables (Sepal.Length, Sepal.Width, and Petal.Length) to predict the Species. Finally, we plot the decision tree with plot() function and add text labels to the tree with text() function.

This is a basic example of how to make a decision tree in R. There are many other options available in the rpart package that can be used to customize the decision tree such as controlling the complexity of the tree and pruning it.

gistlibby LogSnag