The necessary libraries have been provided

Create a dataframe called penguins (you should already have this csv file from previous exercises) perform some explroatory data analysis on your dataframe with str. The data contains NA’s which need to be removed before proceding to KNN

# Load the penguins dataset (your code below)
penguins <- read.csv("C://Users//Gurvinder//Desktop//Data Analytics//Assignments//Predictive Analytics//KNN//penguins.csv")

# Check the structure of the dataset, see if there are any NA's

str(penguins)
## 'data.frame':    344 obs. of  8 variables:
##  $ species          : chr  "Adelie" "Adelie" "Adelie" "Adelie" ...
##  $ island           : chr  "Torgersen" "Torgersen" "Torgersen" "Torgersen" ...
##  $ bill_length_mm   : num  39.1 39.5 40.3 NA 36.7 39.3 38.9 39.2 34.1 42 ...
##  $ bill_depth_mm    : num  18.7 17.4 18 NA 19.3 20.6 17.8 19.6 18.1 20.2 ...
##  $ flipper_length_mm: int  181 186 195 NA 193 190 181 195 193 190 ...
##  $ body_mass_g      : int  3750 3800 3250 NA 3450 3650 3625 4675 3475 4250 ...
##  $ sex              : chr  "male" "female" "female" "" ...
##  $ year             : int  2007 2007 2007 2007 2007 2007 2007 2007 2007 2007 ...
num_NA <- sum(is.na(penguins))

cat("Number of NA values in the dataset:", num_NA, "\n")
## Number of NA values in the dataset: 8
# You should find 19 NA's in the dataset - we need to remove before running knn

penguins <- na.omit(penguins)

partition your data into training and testing

# Split the data into training and testing sets

set.seed(123)
ind <- createDataPartition(penguins$species, p = .75, list = FALSE)
train_data <- penguins[ind, ]
test_data <- penguins[-ind, ]
# Create a KNN model using the k-Nearest Neighbors algorithm. Lets use K=3 to start but please try other values of K to test your model accuracy - then run your final version using the best k

model <- knn(train_data[, c("bill_length_mm", "bill_depth_mm", "flipper_length_mm", "body_mass_g")],
             test_data[, c("bill_length_mm", "bill_depth_mm", "flipper_length_mm", "body_mass_g")],
             cl = train_data$species, k = 3)
# Check the accuracy of the model
# accuracy can be calculated by using the a formula similar to this
# accuracy <- sum(your_model == test_date$species) / nrow(test_data)
# cat("Accuracy:", accuracy, "\n")
# which concatenates the text along with your accuracy variable value

accuracy <- sum(model == test_data$species) / nrow(test_data)
cat("Accuracy:", accuracy, "\n")
## Accuracy: 0.8571429
# Create a confusion matrix where Actual = your test data species, and predicted = your_model
# confusion_matrix <- table(Actual = ???, Predicted = ???)

confusion_matrix <- table(Actual = test_data$species, Predicted = model)

# Print the confusion matrix

print(confusion_matrix)
##            Predicted
## Actual      Adelie Chinstrap Gentoo
##   Adelie        33         2      2
##   Chinstrap      4        11      2
##   Gentoo         2         0     28