Learn Before
Concept

Implementation of Classification Trees in R

Step 1: Change a numerical variable into a categorical variable. Binary (adds a new column): newcolumnname = ifelse(columnname <= threshold, "No", "Yes") newdataset = data.frame(dataset, newcolumnname)

Multi-category (changes original column): data$column[criterion] <- 'category name1'

Step 2: Build a model using the tree() function: model <- tree(formula = outputcolumn ~ ., data = dataframe)

Step 3: Predict on test data: tree.pred = predict(model, testdata, type = "class") table(tree.pred, testlabel)

Step 4: Prune the tree using cv.tree() to determine optimal complexity: cv.carseats = cv.tree(tree.carseats, FUN = prune.misclass) The argument FUN = prune.misclass uses the classification error rate to guide cross-validation and pruning, rather than the default deviance.

0

2

Updated 2026-06-29

Tags

Data Science