How to write decision tree code in the R language?
In the R language, the rpart library can be used to build decision tree models. Here is a simple example code for constructing a decision tree.
# 导入rpart库
library(rpart)
# 导入数据集
data(iris)
# 创建决策树模型
model <- rpart(Species ~ ., data = iris)
# 打印决策树模型
print(model)
This code utilizes the classic Iris dataset to build a decision tree. The rpart function is used in constructing the model, with Species as the target variable and ‘.’ representing all other variables as predictors. Finally, the constructed decision tree model is printed using the print function.
You can make corresponding adjustments and modifications according to your own dataset and requirements.