Load the libraries
library(randomForest)
## Warning: package 'randomForest' was built under R version 4.2.2
## randomForest 4.7-1.1
## Type rfNews() to see new features/changes/bug fixes.
library(caret)
## Warning: package 'caret' was built under R version 4.2.1
## Loading required package: ggplot2
##
## Attaching package: 'ggplot2'
## The following object is masked from 'package:randomForest':
##
## margin
## Loading required package: lattice
Split the data into training and testing sets
set.seed(123)
# train_index <- createDataPartition(iris$Species, p = 0.7, list = FALSE)
# train_data <- iris[train_index, ]
# test_data <- iris[-train_index, ]
indices <- sample(1:nrow(iris), size = 0.7 * nrow(iris))
train_data <- iris[indices, ]
test_data <- iris[-indices, ]
Train the random forest model
model <- randomForest(Species ~ ., data = train_data, ntree = 100)
Make predictions on the test data
predictions <- predict(model, test_data[, -5])
Calculate the confusion matrix
conf_matrix <- table(Actual = test_data[, 5], Predicted = predictions)
Print the results
cat("Accuracy:", accuracy, "\n")
## Accuracy: 0.9777778
cat("Confusion Matrix:\n", conf_matrix, "\n")
## Confusion Matrix:
## 14 0 0 0 17 0 0 1 13
cat("Precision:", precision, "\n")
## Precision: 0.9444444
cat("Recall:", recall, "\n")
## Recall: 1
cat("F1 Score:", f1_score, "\n")
## F1 Score: 0.9714286