Importing the dataset
dataset = read.csv('C:/RClass/Position_Salaries.csv')
dataset = dataset[2:3]
Fitting Decision Tree Regression to the dataset
# install.packages('rpart')
library(rpart)
regressor = rpart(formula = Salary ~.,
data = dataset,
control = rpart.control(minsplit = 1))
Predicting a new result
y_pred = predict(regressor, data.frame(Level = 6.5))
Visualizaing the Decision Tree Regression Results
library(ggplot2)
## Warning: package 'ggplot2' was built under R version 4.1.3
ggplot() +
geom_point(aes(x=dataset$Level, y=dataset$Salary),
color='red') +
geom_line(aes(x=dataset$Level, y=predict(regressor, newdata=dataset)),
color='blue') +
ggtitle('Truth or Bluff (Decision Tree Regression)') +
xlab('Level') + ylab('Salary')

Visualizaing the Decision Tree Regression Results (for higher
resolution and smoother curve)
library(ggplot2)
x_grid = seq(min(dataset$Level), max(dataset$Level), 0.1)
ggplot() +
geom_point(aes(x=dataset$Level, y=dataset$Salary),
color='red') +
geom_line(aes(x=x_grid, y=predict(regressor, newdata=data.frame(Level=x_grid))),
color='blue') +
ggtitle('Truth or Bluff (Decision Tree Regression)') +
xlab('Level') + ylab('Salary')
