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

library(cluster)
library(tidyverse)
## Warning: package 'ggplot2' was built under R version 4.3.2
## Warning: package 'stringr' was built under R version 4.3.2
## Warning: package 'lubridate' was built under R version 4.3.2
## ── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
## ✔ dplyr     1.1.3     ✔ readr     2.1.4
## ✔ forcats   1.0.0     ✔ stringr   1.5.1
## ✔ ggplot2   3.4.4     ✔ tibble    3.2.1
## ✔ lubridate 1.9.3     ✔ tidyr     1.3.0
## ✔ purrr     1.0.2     
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ dplyr::filter() masks stats::filter()
## ✖ dplyr::lag()    masks stats::lag()
## ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
library(ggplot2)


# Read Data
mammals <- read_csv("C:/Users/Dell/Downloads/mammal_Sleep.csv")
## New names:
## Rows: 83 Columns: 12
## ── Column specification
## ──────────────────────────────────────────────────────── Delimiter: "," chr
## (5): name, genus, vore, order, conservation dbl (7): ...1, sleep_total,
## sleep_rem, sleep_cycle, awake, brainwt, bodywt
## ℹ Use `spec()` to retrieve the full column specification for this data. ℹ
## Specify the column types or set `show_col_types = FALSE` to quiet this message.
## • `` -> `...1`
# View Data
View(mammals)

# Check Structure
str(mammals)
## spc_tbl_ [83 × 12] (S3: spec_tbl_df/tbl_df/tbl/data.frame)
##  $ ...1        : num [1:83] 1 2 3 4 5 6 7 8 9 10 ...
##  $ name        : chr [1:83] "Cheetah" "Owl monkey" "Mountain beaver" "Greater short-tailed shrew" ...
##  $ genus       : chr [1:83] "Acinonyx" "Aotus" "Aplodontia" "Blarina" ...
##  $ vore        : chr [1:83] "carni" "omni" "herbi" "omni" ...
##  $ order       : chr [1:83] "Carnivora" "Primates" "Rodentia" "Soricomorpha" ...
##  $ conservation: chr [1:83] "lc" NA "nt" "lc" ...
##  $ sleep_total : num [1:83] 12.1 17 14.4 14.9 4 14.4 8.7 7 10.1 3 ...
##  $ sleep_rem   : num [1:83] NA 1.8 2.4 2.3 0.7 2.2 1.4 NA 2.9 NA ...
##  $ sleep_cycle : num [1:83] NA NA NA 0.133 0.667 ...
##  $ awake       : num [1:83] 11.9 7 9.6 9.1 20 9.6 15.3 17 13.9 21 ...
##  $ brainwt     : num [1:83] NA 0.0155 NA 0.00029 0.423 NA NA NA 0.07 0.0982 ...
##  $ bodywt      : num [1:83] 50 0.48 1.35 0.019 600 ...
##  - attr(*, "spec")=
##   .. cols(
##   ..   ...1 = col_double(),
##   ..   name = col_character(),
##   ..   genus = col_character(),
##   ..   vore = col_character(),
##   ..   order = col_character(),
##   ..   conservation = col_character(),
##   ..   sleep_total = col_double(),
##   ..   sleep_rem = col_double(),
##   ..   sleep_cycle = col_double(),
##   ..   awake = col_double(),
##   ..   brainwt = col_double(),
##   ..   bodywt = col_double()
##   .. )
##  - attr(*, "problems")=<externalptr>
# SELECT COLUMN FOR K-means clustering
mammals_subset <- na.omit(mammals[, c("sleep_total", "sleep_rem")])

# K-means Clustering
kmeans_model <- kmeans(mammals_subset, centers = 4)
kmeans_model$centers
##   sleep_total sleep_rem
## 1    9.561538 1.6884615
## 2   13.892857 2.3500000
## 3    4.364286 0.6571429
## 4   18.500000 4.0571429
# Set a max value for k (adjust as needed)
max_k <- 4

# Create an empty dataframe to store results
results_df <- data.frame()

# Create a list to store centroids
centroids_list <- list()

# Iterate over values of k
for (k in 1:max_k) {
  set.seed(123)
  kmeans_model <- kmeans(mammals_subset, centers = k)
  results_df <- rbind(results_df, data.frame(k = k, tot_withinss = kmeans_model$tot.withinss))
  centroids_list[[k]] <- as.data.frame(kmeans_model$centers)
}

# Create a line plot of k versus tot_withinss
ggplot(results_df, aes(x = k, y = tot_withinss)) +
  geom_line() +
  labs(title = "Elbow plot for k-means clustering with centroid",
       x = "Number of clusters (k)",
       y = "Total within-cluster sum of squares") +
  scale_x_continuous(breaks = seq(1, max_k, 4))

# Create a scatterplot of the newly clustered data
mammals_subset_clustered <- cbind(mammals_subset, cluster = as.factor(kmeans_model$cluster))
ggplot(mammals_subset_clustered, aes(x = sleep_total, y = sleep_rem, color = cluster)) +
  geom_point() +
  ggtitle("Clustered Data") +
  xlab("Total Sleep") +
  ylab("REM Sleep") +
  geom_point(data = centroids_list[[4]], aes(x = sleep_total, y = sleep_rem), color = "black", size = 10, alpha = 0.5) +
  geom_text(data = centroids_list[[4]], aes(x = sleep_total, y = sleep_rem, label = row.names(centroids_list[[4]])), color = "black", size = 4, vjust = -1, hjust = -1)