R Markdown

This is an R Markdown document. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. For more details on using R Markdown see http://rmarkdown.rstudio.com.

When you click the Knit button a document will be generated that includes both content as well as the output of any embedded R code chunks within the document. You can embed an R code chunk like this:

summary(cars)
##      speed           dist       
##  Min.   : 4.0   Min.   :  2.00  
##  1st Qu.:12.0   1st Qu.: 26.00  
##  Median :15.0   Median : 36.00  
##  Mean   :15.4   Mean   : 42.98  
##  3rd Qu.:19.0   3rd Qu.: 56.00  
##  Max.   :25.0   Max.   :120.00

Including Plots

You can also embed plots, for example:

Note that the echo = FALSE parameter was added to the code chunk to prevent printing of the R code that generated the plot.

Load the penguins dataset (your code below)

library(readxl)
library(caret)
## Warning: package 'caret' was built under R version 4.3.2
## Loading required package: ggplot2
## Warning: package 'ggplot2' was built under R version 4.3.2
## Loading required package: lattice
library(class)
## Warning: package 'class' was built under R version 4.3.2
library(readxl)
penguins <- read_excel("penguins.xlsx")
View(penguins)

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

str(penguins)
## tibble [344 × 8] (S3: tbl_df/tbl/data.frame)
##  $ species          : chr [1:344] "Adelie" "Adelie" "Adelie" "Adelie" ...
##  $ island           : chr [1:344] "Torgersen" "Torgersen" "Torgersen" "Torgersen" ...
##  $ bill_length_mm   : num [1:344] 39.1 39.5 40.3 NA 36.7 39.3 38.9 39.2 34.1 42 ...
##  $ bill_depth_mm    : num [1:344] 18.7 17.4 18 NA 19.3 20.6 17.8 19.6 18.1 20.2 ...
##  $ flipper_length_mm: num [1:344] 181 186 195 NA 193 190 181 195 193 190 ...
##  $ body_mass_g      : num [1:344] 3750 3800 3250 NA 3450 ...
##  $ sex              : chr [1:344] "male" "female" "female" NA ...
##  $ year             : num [1:344] 2007 2007 2007 2007 2007 ...

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)  # for reproducibility
train_indices <- sample(1:nrow(penguins),nrow(penguins)*0.7)
train_data <- penguins[train_indices, ]
test_data <- penguins[-train_indices,]
# 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


# Partition your data into training and testing
set.seed(123)  # for reproducibility
train_indices <- sample(1:nrow(penguins), nrow(penguins) * 0.7)
train_data <- penguins[train_indices, ]
test_data <- penguins[-train_indices, ]
# Create a KNN model using the k-Nearest Neighbors algorithm. 
# Let's use K=3 to start, but please try other values of K to test your model accuracy.
k <- 3

# Create a KNN model with K=3
# Separate predictors and class labels in the training data
train_predictors <- train_data[, -5]  # Exclude the 'sex' column
train_class_labels <- train_data$island
# Use the correct training data in the knn function
knn_model <- knn(train = train_data[, c("bill_length_mm", "bill_depth_mm", "flipper_length_mm", "body_mass_g")],
                 test = test_data[, c("bill_length_mm", "bill_depth_mm", "flipper_length_mm", "body_mass_g")],
                 cl = train_data$island,
                 k = 3)

accuracy <- sum(knn_model == test_data$island) / nrow(test_data)
cat("Accuracy:", accuracy, "\n")
## Accuracy: 0.62
# Print the confusion matrix to evaluate the model

conf_matrix <- table(Actual = test_data$island, Predicted = knn_model)
print(conf_matrix)
##            Predicted
## Actual      Biscoe Dream Torgersen
##   Biscoe        34    12         1
##   Dream          4    26         9
##   Torgersen      3     9         2