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

Load the data

data(iris)

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)

Evaluate the perform of prediction model

# Calculate the accuracy
accuracy <- mean(predictions == test_data[, 5])

# Calculate the precision
precision <- conf_matrix[2, 2] / sum(conf_matrix[2, ])

# Calculate the recall
recall <- conf_matrix[2, 2] / sum(conf_matrix[, 2])

# Calculate the F1 score
f1_score <- 2 * (precision * recall) / (precision + recall)