Business Intelligence Project

Student Details

Student ID Number 136804
Student Name Joy Mutai
BBIT 4.2 Group C
BI Project Group Name/ID (if applicable) …

#####Data Imputation #Preprocessing

.libPaths()
## [1] "C:/Users/Joy/R-4.3.1/library"
lapply(.libPaths(), list.files)
## [[1]]
##   [1] "abind"           "adabag"          "Amelia"          "arules"         
##   [5] "arulesViz"       "askpass"         "av"              "backports"      
##   [9] "base"            "base64enc"       "BayesFactor"     "bit"            
##  [13] "bit64"           "blob"            "boot"            "brew"           
##  [17] "brio"            "broom"           "bslib"           "C50"            
##  [21] "ca"              "cachem"          "Cairo"           "callr"          
##  [25] "car"             "carData"         "caret"           "caretEnsemble"  
##  [29] "cellranger"      "circlize"        "class"           "classInt"       
##  [33] "cli"             "clipr"           "clock"           "cluster"        
##  [37] "coda"            "codetools"       "collections"     "colorspace"     
##  [41] "colourpicker"    "combinat"        "commonmark"      "compiler"       
##  [45] "conflicted"      "ConsRank"        "contfrac"        "corrplot"       
##  [49] "covr"            "cowplot"         "cpp11"           "crayon"         
##  [53] "crosstalk"       "Cubist"          "curl"            "cyclocomp"      
##  [57] "data.table"      "datasets"        "DBI"             "dbplyr"         
##  [61] "dendextend"      "desc"            "deSolve"         "diagram"        
##  [65] "diffobj"         "digest"          "doParallel"      "dplyr"          
##  [69] "DT"              "dtplyr"          "e1071"           "ellipse"        
##  [73] "ellipsis"        "elliptic"        "emmeans"         "estimability"   
##  [77] "evaluate"        "factoextra"      "FactoMineR"      "fansi"          
##  [81] "farver"          "fastICA"         "fastmap"         "feather"        
##  [85] "flashClust"      "fontawesome"     "forcats"         "foreach"        
##  [89] "foreign"         "formatR"         "formattable"     "Formula"        
##  [93] "fs"              "future"          "future.apply"    "gapminder"      
##  [97] "gargle"          "gclus"           "generics"        "ggcorrplot"     
## [101] "ggforce"         "ggplot2"         "ggpubr"          "ggraph"         
## [105] "ggrepel"         "ggsci"           "ggsignif"        "gifski"         
## [109] "glmnet"          "GlobalOptions"   "globals"         "glue"           
## [113] "googledrive"     "googlesheets4"   "gower"           "graphics"       
## [117] "graphlayouts"    "grDevices"       "grid"            "gridExtra"      
## [121] "gtable"          "gtools"          "hardhat"         "haven"          
## [125] "highr"           "hms"             "htmltools"       "htmlwidgets"    
## [129] "httpuv"          "httr"            "hunspell"        "hypergeo"       
## [133] "ids"             "igraph"          "inum"            "ipred"          
## [137] "IRdisplay"       "isoband"         "iterators"       "janeaustenr"    
## [141] "jomo"            "jpeg"            "jquerylib"       "jsonlite"       
## [145] "kableExtra"      "kernlab"         "KernSmooth"      "klaR"           
## [149] "knitr"           "labeling"        "labelled"        "languageserver" 
## [153] "later"           "lattice"         "lava"            "lazyeval"       
## [157] "leaps"           "libcoin"         "LiblineaR"       "lifecycle"      
## [161] "lintr"           "listenv"         "lme4"            "lmtest"         
## [165] "lubridate"       "magick"          "magrittr"        "markdown"       
## [169] "MASS"            "Matrix"          "MatrixModels"    "memery"         
## [173] "memoise"         "methods"         "mgcv"            "mice"           
## [177] "mime"            "miniUI"          "minqa"           "mitml"          
## [181] "mlbench"         "mockr"           "ModelMetrics"    "modelr"         
## [185] "multcompView"    "munsell"         "mvtnorm"         "naivebayes"     
## [189] "naniar"          "NHANES"          "nlme"            "nloptr"         
## [193] "nnet"            "norm"            "numDeriv"        "openssl"        
## [197] "ordinal"         "packrat"         "pan"             "parallel"       
## [201] "parallelly"      "partykit"        "pbapply"         "pbkrtest"       
## [205] "pdftools"        "permute"         "pillar"          "pkgbuild"       
## [209] "pkgconfig"       "pkgload"         "plotly"          "plumber"        
## [213] "plyr"            "png"             "polyclip"        "polynom"        
## [217] "praise"          "prettyunits"     "pROC"            "processx"       
## [221] "prodlim"         "progress"        "progressr"       "promises"       
## [225] "proxy"           "ps"              "purrr"           "qap"            
## [229] "qpdf"            "quantreg"        "questionr"       "R.cache"        
## [233] "R.methodsS3"     "R.oo"            "R.utils"         "R6"             
## [237] "radarchart"      "ragg"            "randomForest"    "RANN"           
## [241] "rappdirs"        "RColorBrewer"    "Rcpp"            "RcppArmadillo"  
## [245] "RcppEigen"       "readr"           "readxl"          "recipes"        
## [249] "registry"        "rematch"         "rematch2"        "remotes"        
## [253] "renv"            "repr"            "reprex"          "reshape2"       
## [257] "rex"             "rgl"             "rlang"           "rlist"          
## [261] "rmarkdown"       "roxygen2"        "rpart"           "rprojroot"      
## [265] "RRF"             "rsconnect"       "rstatix"         "rstudioapi"     
## [269] "rsvg"            "rvest"           "sass"            "scales"         
## [273] "scatterplot3d"   "selectr"         "seriation"       "shape"          
## [277] "shiny"           "shinyBS"         "shinycssloaders" "shinyjs"        
## [281] "showtext"        "showtextdb"      "SnowballC"       "sodium"         
## [285] "sourcetools"     "SparseM"         "spatial"         "spelling"       
## [289] "splines"         "SQUAREM"         "stats"           "stats4"         
## [293] "stringi"         "stringr"         "styler"          "survival"       
## [297] "svglite"         "swagger"         "sys"             "sysfonts"       
## [301] "systemfonts"     "tcltk"           "tesseract"       "testthat"       
## [305] "textdata"        "textshaping"     "tibble"          "tidygraph"      
## [309] "tidyr"           "tidyselect"      "tidytext"        "tidyverse"      
## [313] "timechange"      "timeDate"        "tinytex"         "tokenizers"     
## [317] "tools"           "translations"    "TSP"             "tweenr"         
## [321] "tzdb"            "ucminf"          "UpSetR"          "utf8"           
## [325] "utils"           "uuid"            "vcd"             "vctrs"          
## [329] "vegan"           "viridis"         "viridisLite"     "visdat"         
## [333] "visNetwork"      "vroom"           "waldo"           "webp"           
## [337] "webshot"         "webutils"        "widyr"           "withr"          
## [341] "wordcloud2"      "xfun"            "XML"             "xml2"           
## [345] "xmlparsedata"    "xtable"          "yaml"            "yarrr"          
## [349] "zoo"

#Install Packages

####Step1: Installing necessary packages

if (!is.element("languageserver", installed.packages()[, 1])) {
  install.packages("languageserver", dependencies = TRUE,
                   repos = "https://cloud.r-project.org")
}
require("languageserver")
## Loading required package: languageserver
# This requires the "NHANES" package available in R

if (!is.element("NHANES", installed.packages()[, 1])) {
  install.packages("NHANES", dependencies = TRUE,
                   repos = "https://cloud.r-project.org")
}
require("NHANES")
## Loading required package: NHANES
## dplyr ----
if (!is.element("dplyr", installed.packages()[, 1])) {
  install.packages("dplyr", dependencies = TRUE,
                   repos = "https://cloud.r-project.org")
}
require("dplyr")
## Loading required package: dplyr

## 
## Attaching package: 'dplyr'

## The following objects are masked from 'package:stats':
## 
##     filter, lag

## The following objects are masked from 'package:base':
## 
##     intersect, setdiff, setequal, union
## naniar ----
# Documentation:
#   https://cran.r-project.org/package=naniar or
#   https://www.rdocumentation.org/packages/naniar/versions/1.0.0
if (!is.element("naniar", installed.packages()[, 1])) {
  install.packages("naniar", dependencies = TRUE,
                   repos = "https://cloud.r-project.org")
}
require("naniar")
## Loading required package: naniar
## ggplot2 ----
# We require the "ggplot2" package to create more appealing visualizations
if (!is.element("ggplot2", installed.packages()[, 1])) {
  install.packages("ggplot2", dependencies = TRUE,
                   repos = "https://cloud.r-project.org")
}
require("ggplot2")
## Loading required package: ggplot2
## MICE ----
# We use the MICE package to perform data imputation
if (!is.element("mice", installed.packages()[, 1])) {
  install.packages("mice", dependencies = TRUE,
                   repos = "https://cloud.r-project.org")
}
require("mice")
## Loading required package: mice

## 
## Attaching package: 'mice'

## The following object is masked from 'package:stats':
## 
##     filter

## The following objects are masked from 'package:base':
## 
##     cbind, rbind
## Amelia ----
if (!is.element("Amelia", installed.packages()[, 1])) {
  install.packages("Amelia", dependencies = TRUE,
                   repos = "https://cloud.r-project.org")
}
require("Amelia")
## Loading required package: Amelia

## Loading required package: Rcpp

## ## 
## ## Amelia II: Multiple Imputation
## ## (Version 1.8.1, built: 2022-11-18)
## ## Copyright (C) 2005-2023 James Honaker, Gary King and Matthew Blackwell
## ## Refer to http://gking.harvard.edu/amelia/ for more information
## ##
library(dplyr)

###Load dataset

library(readr)
housing <- read_csv("data/housing.csv", col_types = cols(longitude = col_double(), 
                                                         latitude = col_double(), housing_median_age = col_number(), 
                                                         total_rooms = col_number(), total_bedrooms = col_number(), 
                                                         population = col_number(), households = col_number(), 
                                                         median_income = col_number(), ocean_proximity = col_character(), 
                                                         median_house_value = col_number()))
View(housing)

STEP 2. Create a subset of the variables/features

housing_subset_features <- housing %>%
  select(longitude, latitude, housing_median_age, total_rooms, total_bedrooms,
         population, households, median_income, ocean_proximity, median_house_value)

# Subset of rows
# We then select 500 random observations to be included in the dataset
rand_ind <- sample(seq_len(nrow(housing_subset_features)), 500)
housing_subset_rows <- housing_subset_features[rand_ind, ]

# Assuming 'housing' is your dataset
# Replace the variable names accordingly

# Load necessary libraries
library(naniar) 

STEP 3. Confirm the “missingness” in the Dataset before Imputation

# Are there missing values in the dataset?
any_na(housing)
## [1] TRUE
# How many?
n_miss(housing)
## [1] 207
# What is the percentage of missing data in the entire dataset?
prop_miss(housing)
## [1] 0.001002907
# How many missing values does each variable have?
housing %>% is.na() %>% colSums()
##          longitude           latitude housing_median_age        total_rooms 
##                  0                  0                  0                  0 
##     total_bedrooms         population         households      median_income 
##                207                  0                  0                  0 
##    ocean_proximity median_house_value 
##                  0                  0
# What is the number and percentage of missing values grouped by
# each variable?
miss_var_summary(housing)
## # A tibble: 10 × 3
##    variable           n_miss pct_miss
##    <chr>               <int>    <dbl>
##  1 total_bedrooms        207     1.00
##  2 longitude               0     0   
##  3 latitude                0     0   
##  4 housing_median_age      0     0   
##  5 total_rooms             0     0   
##  6 population              0     0   
##  7 households              0     0   
##  8 median_income           0     0   
##  9 ocean_proximity         0     0   
## 10 median_house_value      0     0
# What is the number and percentage of missing values grouped by
# each observation?
miss_case_summary(housing)
## # A tibble: 20,640 × 3
##     case n_miss pct_miss
##    <int>  <int>    <dbl>
##  1   291      1       10
##  2   342      1       10
##  3   539      1       10
##  4   564      1       10
##  5   697      1       10
##  6   739      1       10
##  7  1098      1       10
##  8  1351      1       10
##  9  1457      1       10
## 10  1494      1       10
## # ℹ 20,630 more rows
ggplot(housing, aes(x = is.na(total_bedrooms))) +
  geom_bar() +
  scale_x_discrete(labels = c("Not Missing", "Missing")) +
  ylab("Count") +
  xlab("Missing Values")

#####Step 4:Use the MICE package to perform data imputation —-

# Load necessary libraries
library(mice)  # Make sure to have the mice package installed

# Add a new variable 'MAP' based on the given formula
housing <- housing %>%
  mutate(MAP = total_rooms + (1 / 3) * (total_bedrooms - total_rooms))

# Identify somewhat correlated variables for imputation
somewhat_correlated_variables <- quickpred(housing, mincor = 0.3) # nolint

# Impute missing data using mice
housing_mice <- mice(housing, m = 11, method = "pmm",
                     seed = 7,
                     predictorMatrix = somewhat_correlated_variables)
## 
##  iter imp variable
##   1   1  total_bedrooms
##   1   2  total_bedrooms
##   1   3  total_bedrooms
##   1   4  total_bedrooms
##   1   5  total_bedrooms
##   1   6  total_bedrooms
##   1   7  total_bedrooms
##   1   8  total_bedrooms
##   1   9  total_bedrooms
##   1   10  total_bedrooms
##   1   11  total_bedrooms
##   2   1  total_bedrooms
##   2   2  total_bedrooms
##   2   3  total_bedrooms
##   2   4  total_bedrooms
##   2   5  total_bedrooms
##   2   6  total_bedrooms
##   2   7  total_bedrooms
##   2   8  total_bedrooms
##   2   9  total_bedrooms
##   2   10  total_bedrooms
##   2   11  total_bedrooms
##   3   1  total_bedrooms
##   3   2  total_bedrooms
##   3   3  total_bedrooms
##   3   4  total_bedrooms
##   3   5  total_bedrooms
##   3   6  total_bedrooms
##   3   7  total_bedrooms
##   3   8  total_bedrooms
##   3   9  total_bedrooms
##   3   10  total_bedrooms
##   3   11  total_bedrooms
##   4   1  total_bedrooms
##   4   2  total_bedrooms
##   4   3  total_bedrooms
##   4   4  total_bedrooms
##   4   5  total_bedrooms
##   4   6  total_bedrooms
##   4   7  total_bedrooms
##   4   8  total_bedrooms
##   4   9  total_bedrooms
##   4   10  total_bedrooms
##   4   11  total_bedrooms
##   5   1  total_bedrooms
##   5   2  total_bedrooms
##   5   3  total_bedrooms
##   5   4  total_bedrooms
##   5   5  total_bedrooms
##   5   6  total_bedrooms
##   5   7  total_bedrooms
##   5   8  total_bedrooms
##   5   9  total_bedrooms
##   5   10  total_bedrooms
##   5   11  total_bedrooms

## Warning: Number of logged events: 1
# Visualize imputed data using strip plots
stripplot(housing_mice,
          MAP ~ median_income | .imp,
          pch = 20, cex = 1)

stripplot(housing_mice,
          MAP ~ population | .imp,
          pch = 20, cex = 1)

## Impute the missing data
# Create imputed data for the final dataset using the mice::complete() function
housing_imputed <- mice::complete(housing_mice, 1)

# Load necessary libraries
library(Amelia)  # Make sure to have the Amelia package installed

STEP 5. Confirm the “missingness” in the Imputed Dataset —-

# A textual confirmation that the dataset has no more missing values in any
# feature:
miss_var_summary(housing_imputed)
## # A tibble: 11 × 3
##    variable           n_miss pct_miss
##    <chr>               <int>    <dbl>
##  1 MAP                   207     1.00
##  2 longitude               0     0   
##  3 latitude                0     0   
##  4 housing_median_age      0     0   
##  5 total_rooms             0     0   
##  6 total_bedrooms          0     0   
##  7 population              0     0   
##  8 households              0     0   
##  9 median_income           0     0   
## 10 ocean_proximity         0     0   
## 11 median_house_value      0     0
# A visual confirmation that the dataset has no more missing values in any
# feature:
missmap(housing_imputed)

#########################
# Are there missing values in the dataset?
any_na(housing_imputed)
## [1] TRUE
# How many?
n_miss(housing_imputed)
## [1] 207
# What is the percentage of missing data in the entire dataset?
prop_miss(housing_imputed)
## [1] 0.0009117336
# How many missing values does each variable have?
housing_imputed %>% is.na() %>% colSums()
##          longitude           latitude housing_median_age        total_rooms 
##                  0                  0                  0                  0 
##     total_bedrooms         population         households      median_income 
##                  0                  0                  0                  0 
##    ocean_proximity median_house_value                MAP 
##                  0                  0                207
# What is the number and percentage of missing values grouped by
# each variable?
miss_var_summary(housing_imputed)
## # A tibble: 11 × 3
##    variable           n_miss pct_miss
##    <chr>               <int>    <dbl>
##  1 MAP                   207     1.00
##  2 longitude               0     0   
##  3 latitude                0     0   
##  4 housing_median_age      0     0   
##  5 total_rooms             0     0   
##  6 total_bedrooms          0     0   
##  7 population              0     0   
##  8 households              0     0   
##  9 median_income           0     0   
## 10 ocean_proximity         0     0   
## 11 median_house_value      0     0
# What is the number and percentage of missing values grouped by
# each observation?
miss_case_summary(housing_imputed)
## # A tibble: 20,640 × 3
##     case n_miss pct_miss
##    <int>  <int>    <dbl>
##  1   291      1     9.09
##  2   342      1     9.09
##  3   539      1     9.09
##  4   564      1     9.09
##  5   697      1     9.09
##  6   739      1     9.09
##  7  1098      1     9.09
##  8  1351      1     9.09
##  9  1457      1     9.09
## 10  1494      1     9.09
## # ℹ 20,630 more rows
# Which variables contain the most missing values?
gg_miss_var(housing_imputed)

# Where are missing values located (the shaded regions in the plot)?
vis_miss(housing_imputed) + theme(axis.text.x = element_text(angle = 80))

# Note: The following command should give you an error stating that at least 2
# variables should have missing data for the plot to be created.
# Which combinations of variables are missing together?
# gg_miss_upset(housing_imputed)

# Assuming 'housing_imputed' is your imputed dataset
# Replace the variable names accordingly

# Create a heatmap of "missingness" broken down by "ocean_proximity"
# First, confirm that the "ocean_proximity" variable is a categorical variable
is.factor(housing_imputed$ocean_proximity)
## [1] FALSE
# Second, create the visualization
gg_miss_fct(housing_imputed, fct = ocean_proximity)

# Create a heatmap of "missingness" broken down by "oceanproximity"
# First, confirm that the "oceanproximity" variable is a categorical variable
is.factor(housing_imputed$ocean_proximity)
## [1] FALSE
# Second, create the visualization
gg_miss_fct(housing_imputed, fct = ocean_proximity)

#####Data Transformation

.libPaths()
## [1] "C:/Users/Joy/R-4.3.1/library"
lapply(.libPaths(), list.files)
## [[1]]
##   [1] "abind"           "adabag"          "Amelia"          "arules"         
##   [5] "arulesViz"       "askpass"         "av"              "backports"      
##   [9] "base"            "base64enc"       "BayesFactor"     "bit"            
##  [13] "bit64"           "blob"            "boot"            "brew"           
##  [17] "brio"            "broom"           "bslib"           "C50"            
##  [21] "ca"              "cachem"          "Cairo"           "callr"          
##  [25] "car"             "carData"         "caret"           "caretEnsemble"  
##  [29] "cellranger"      "circlize"        "class"           "classInt"       
##  [33] "cli"             "clipr"           "clock"           "cluster"        
##  [37] "coda"            "codetools"       "collections"     "colorspace"     
##  [41] "colourpicker"    "combinat"        "commonmark"      "compiler"       
##  [45] "conflicted"      "ConsRank"        "contfrac"        "corrplot"       
##  [49] "covr"            "cowplot"         "cpp11"           "crayon"         
##  [53] "crosstalk"       "Cubist"          "curl"            "cyclocomp"      
##  [57] "data.table"      "datasets"        "DBI"             "dbplyr"         
##  [61] "dendextend"      "desc"            "deSolve"         "diagram"        
##  [65] "diffobj"         "digest"          "doParallel"      "dplyr"          
##  [69] "DT"              "dtplyr"          "e1071"           "ellipse"        
##  [73] "ellipsis"        "elliptic"        "emmeans"         "estimability"   
##  [77] "evaluate"        "factoextra"      "FactoMineR"      "fansi"          
##  [81] "farver"          "fastICA"         "fastmap"         "feather"        
##  [85] "flashClust"      "fontawesome"     "forcats"         "foreach"        
##  [89] "foreign"         "formatR"         "formattable"     "Formula"        
##  [93] "fs"              "future"          "future.apply"    "gapminder"      
##  [97] "gargle"          "gclus"           "generics"        "ggcorrplot"     
## [101] "ggforce"         "ggplot2"         "ggpubr"          "ggraph"         
## [105] "ggrepel"         "ggsci"           "ggsignif"        "gifski"         
## [109] "glmnet"          "GlobalOptions"   "globals"         "glue"           
## [113] "googledrive"     "googlesheets4"   "gower"           "graphics"       
## [117] "graphlayouts"    "grDevices"       "grid"            "gridExtra"      
## [121] "gtable"          "gtools"          "hardhat"         "haven"          
## [125] "highr"           "hms"             "htmltools"       "htmlwidgets"    
## [129] "httpuv"          "httr"            "hunspell"        "hypergeo"       
## [133] "ids"             "igraph"          "inum"            "ipred"          
## [137] "IRdisplay"       "isoband"         "iterators"       "janeaustenr"    
## [141] "jomo"            "jpeg"            "jquerylib"       "jsonlite"       
## [145] "kableExtra"      "kernlab"         "KernSmooth"      "klaR"           
## [149] "knitr"           "labeling"        "labelled"        "languageserver" 
## [153] "later"           "lattice"         "lava"            "lazyeval"       
## [157] "leaps"           "libcoin"         "LiblineaR"       "lifecycle"      
## [161] "lintr"           "listenv"         "lme4"            "lmtest"         
## [165] "lubridate"       "magick"          "magrittr"        "markdown"       
## [169] "MASS"            "Matrix"          "MatrixModels"    "memery"         
## [173] "memoise"         "methods"         "mgcv"            "mice"           
## [177] "mime"            "miniUI"          "minqa"           "mitml"          
## [181] "mlbench"         "mockr"           "ModelMetrics"    "modelr"         
## [185] "multcompView"    "munsell"         "mvtnorm"         "naivebayes"     
## [189] "naniar"          "NHANES"          "nlme"            "nloptr"         
## [193] "nnet"            "norm"            "numDeriv"        "openssl"        
## [197] "ordinal"         "packrat"         "pan"             "parallel"       
## [201] "parallelly"      "partykit"        "pbapply"         "pbkrtest"       
## [205] "pdftools"        "permute"         "pillar"          "pkgbuild"       
## [209] "pkgconfig"       "pkgload"         "plotly"          "plumber"        
## [213] "plyr"            "png"             "polyclip"        "polynom"        
## [217] "praise"          "prettyunits"     "pROC"            "processx"       
## [221] "prodlim"         "progress"        "progressr"       "promises"       
## [225] "proxy"           "ps"              "purrr"           "qap"            
## [229] "qpdf"            "quantreg"        "questionr"       "R.cache"        
## [233] "R.methodsS3"     "R.oo"            "R.utils"         "R6"             
## [237] "radarchart"      "ragg"            "randomForest"    "RANN"           
## [241] "rappdirs"        "RColorBrewer"    "Rcpp"            "RcppArmadillo"  
## [245] "RcppEigen"       "readr"           "readxl"          "recipes"        
## [249] "registry"        "rematch"         "rematch2"        "remotes"        
## [253] "renv"            "repr"            "reprex"          "reshape2"       
## [257] "rex"             "rgl"             "rlang"           "rlist"          
## [261] "rmarkdown"       "roxygen2"        "rpart"           "rprojroot"      
## [265] "RRF"             "rsconnect"       "rstatix"         "rstudioapi"     
## [269] "rsvg"            "rvest"           "sass"            "scales"         
## [273] "scatterplot3d"   "selectr"         "seriation"       "shape"          
## [277] "shiny"           "shinyBS"         "shinycssloaders" "shinyjs"        
## [281] "showtext"        "showtextdb"      "SnowballC"       "sodium"         
## [285] "sourcetools"     "SparseM"         "spatial"         "spelling"       
## [289] "splines"         "SQUAREM"         "stats"           "stats4"         
## [293] "stringi"         "stringr"         "styler"          "survival"       
## [297] "svglite"         "swagger"         "sys"             "sysfonts"       
## [301] "systemfonts"     "tcltk"           "tesseract"       "testthat"       
## [305] "textdata"        "textshaping"     "tibble"          "tidygraph"      
## [309] "tidyr"           "tidyselect"      "tidytext"        "tidyverse"      
## [313] "timechange"      "timeDate"        "tinytex"         "tokenizers"     
## [317] "tools"           "translations"    "TSP"             "tweenr"         
## [321] "tzdb"            "ucminf"          "UpSetR"          "utf8"           
## [325] "utils"           "uuid"            "vcd"             "vctrs"          
## [329] "vegan"           "viridis"         "viridisLite"     "visdat"         
## [333] "visNetwork"      "vroom"           "waldo"           "webp"           
## [337] "webshot"         "webutils"        "widyr"           "withr"          
## [341] "wordcloud2"      "xfun"            "XML"             "xml2"           
## [345] "xmlparsedata"    "xtable"          "yaml"            "yarrr"          
## [349] "zoo"

######Step 1:Installing packages

if (require("languageserver")) {
  require("languageserver")
} else {
  install.packages("languageserver", dependencies = TRUE,
                   repos = "https://cloud.r-project.org")
}

## Install Install and Load the Required Packages ----
if (require("mlbench")) {
  require("mlbench")
} else {
  install.packages("mlbench", dependencies = TRUE,
                   repos = "https://cloud.r-project.org")
}
## Loading required package: mlbench
## readr ----
if (require("readr")) {
  require("readr")
} else {
  install.packages("readr", dependencies = TRUE,
                   repos = "https://cloud.r-project.org")
}

## caret ----
if (require("caret")) {
  require("caret")
} else {
  install.packages("caret", dependencies = TRUE,
                   repos = "https://cloud.r-project.org")
}
## Loading required package: caret

## Warning: package 'caret' was built under R version 4.3.2

## Loading required package: lattice
## e1071 ----
if (require("e1071")) {
  require("e1071")
} else {
  install.packages("e1071", dependencies = TRUE,
                   repos = "https://cloud.r-project.org")
}
## Loading required package: e1071

## Warning: package 'e1071' was built under R version 4.3.2
## factoextra ----
if (require("factoextra")) {
  require("factoextra")
} else {
  install.packages("factoextra", dependencies = TRUE,
                   repos = "https://cloud.r-project.org")
}
## Loading required package: factoextra

## Welcome! Want to learn more? See two factoextra-related books at https://goo.gl/ve3WBa
## FactoMineR ----
if (require("FactoMineR")) {
  require("FactoMineR")
} else {
  install.packages("FactoMineR", dependencies = TRUE,
                   repos = "https://cloud.r-project.org")
}
## Loading required package: FactoMineR

STEP 2. Load the Datasets —-

housing <- read_csv("data/housing.csv", col_types = cols(longitude = col_double(), 
                                                         latitude = col_double(), housing_median_age = col_number(), 
                                                         total_rooms = col_number(), total_bedrooms = col_number(), 
                                                         population = col_number(), households = col_number(), 
                                                         median_income = col_number(), ocean_proximity = col_character(), 
                                                         median_house_value = col_number()))

#####Step 3: Scale Data Transform —-

### The Scale Basic Transform on the Boston Housing Dataset ----
# BEFORE

summary(housing)
##    longitude         latitude     housing_median_age  total_rooms   
##  Min.   :-124.3   Min.   :32.54   Min.   : 1.00      Min.   :    2  
##  1st Qu.:-121.8   1st Qu.:33.93   1st Qu.:18.00      1st Qu.: 1448  
##  Median :-118.5   Median :34.26   Median :29.00      Median : 2127  
##  Mean   :-119.6   Mean   :35.63   Mean   :28.64      Mean   : 2636  
##  3rd Qu.:-118.0   3rd Qu.:37.71   3rd Qu.:37.00      3rd Qu.: 3148  
##  Max.   :-114.3   Max.   :41.95   Max.   :52.00      Max.   :39320  
##                                                                     
##  total_bedrooms     population      households     median_income    
##  Min.   :   1.0   Min.   :    3   Min.   :   1.0   Min.   : 0.4999  
##  1st Qu.: 296.0   1st Qu.:  787   1st Qu.: 280.0   1st Qu.: 2.5634  
##  Median : 435.0   Median : 1166   Median : 409.0   Median : 3.5348  
##  Mean   : 537.9   Mean   : 1425   Mean   : 499.5   Mean   : 3.8707  
##  3rd Qu.: 647.0   3rd Qu.: 1725   3rd Qu.: 605.0   3rd Qu.: 4.7432  
##  Max.   :6445.0   Max.   :35682   Max.   :6082.0   Max.   :15.0001  
##  NA's   :207                                                        
##  ocean_proximity    median_house_value
##  Length:20640       Min.   : 14999    
##  Class :character   1st Qu.:119600    
##  Mode  :character   Median :179700    
##                     Mean   :206856    
##                     3rd Qu.:264725    
##                     Max.   :500001    
## 
# Histograms for selected columns in the housing dataset
hist(housing$longitude, main = "Longitude")

hist(housing$latitude, main = "Latitude")

hist(housing$housing_median_age, main = "Housing Median Age")

hist(housing$total_rooms, main = "Total Rooms")

hist(housing$total_bedrooms, main = "Total Bedrooms")

hist(housing$population, main = "Population")

hist(housing$households, main = "Households")

hist(housing$median_income, main = "Median Income")

hist(housing$median_house_value, main = "Median House Value")

# Install and load the caret package
install.packages("caret")
## Warning: package 'caret' is in use and will not be installed
library(caret)

# Create a model for data transformation
model_of_the_transform <- preProcess(housing, method = c("scale"))
print(model_of_the_transform)
## Created from 20433 samples and 10 variables
## 
## Pre-processing:
##   - ignored (1)
##   - scaled (9)
# Apply the transformation to the housing dataset
housing_scale_transform <- predict(model_of_the_transform, housing)

##AFTER
# Summary of the scaled and transformed housing dataset
summary(housing_scale_transform)
##    longitude         latitude     housing_median_age  total_rooms       
##  Min.   :-62.07   Min.   :15.23   Min.   :0.07946    Min.   : 0.000917  
##  1st Qu.:-60.79   1st Qu.:15.89   1st Qu.:1.43021    1st Qu.: 0.663614  
##  Median :-59.14   Median :16.04   Median :2.30423    Median : 0.974966  
##  Mean   :-59.68   Mean   :16.68   Mean   :2.27558    Mean   : 1.208170  
##  3rd Qu.:-58.90   3rd Qu.:17.65   3rd Qu.:2.93988    3rd Qu.: 1.442968  
##  Max.   :-57.05   Max.   :19.64   Max.   :4.13172    Max.   :18.023343  
##                                                                         
##  total_bedrooms       population          households        median_income   
##  Min.   : 0.00237   Min.   : 0.002649   Min.   : 0.002616   Min.   :0.2631  
##  1st Qu.: 0.70245   1st Qu.: 0.694946   1st Qu.: 0.732352   1st Qu.:1.3493  
##  Median : 1.03231   Median : 1.029615   Median : 1.069757   Median :1.8606  
##  Mean   : 1.27643   Mean   : 1.258741   Mean   : 1.306568   Mean   :2.0374  
##  3rd Qu.: 1.53541   3rd Qu.: 1.523230   3rd Qu.: 1.582404   3rd Qu.:2.4967  
##  Max.   :15.29480   Max.   :31.508339   Max.   :15.907734   Max.   :7.8955  
##  NA's   :207                                                                
##  ocean_proximity    median_house_value
##  Length:20640       Min.   :0.130     
##  Class :character   1st Qu.:1.036     
##  Mode  :character   Median :1.557     
##                     Mean   :1.793     
##                     3rd Qu.:2.294     
##                     Max.   :4.333     
## 
# Histograms for selected columns in the scaled and transformed housing dataset
hist(housing_scale_transform$longitude, main = "Longitude")

hist(housing_scale_transform$latitude, main = "Latitude")

hist(housing_scale_transform$housing_median_age, main = "Housing Median Age")

hist(housing_scale_transform$total_rooms, main = "Total Rooms")

hist(housing_scale_transform$total_bedrooms, main = "Total Bedrooms")

hist(housing_scale_transform$population, main = "Population")

hist(housing_scale_transform$households, main = "Households")

hist(housing_scale_transform$median_income, main = "Median Income")

hist(housing_scale_transform$median_house_value, main = "Median House Value")

###Step 4:Apply a Centre Data Transform —-

### The Centre Basic Transform on the Housing Dataset ----
# BEFORE
summary(housing)
##    longitude         latitude     housing_median_age  total_rooms   
##  Min.   :-124.3   Min.   :32.54   Min.   : 1.00      Min.   :    2  
##  1st Qu.:-121.8   1st Qu.:33.93   1st Qu.:18.00      1st Qu.: 1448  
##  Median :-118.5   Median :34.26   Median :29.00      Median : 2127  
##  Mean   :-119.6   Mean   :35.63   Mean   :28.64      Mean   : 2636  
##  3rd Qu.:-118.0   3rd Qu.:37.71   3rd Qu.:37.00      3rd Qu.: 3148  
##  Max.   :-114.3   Max.   :41.95   Max.   :52.00      Max.   :39320  
##                                                                     
##  total_bedrooms     population      households     median_income    
##  Min.   :   1.0   Min.   :    3   Min.   :   1.0   Min.   : 0.4999  
##  1st Qu.: 296.0   1st Qu.:  787   1st Qu.: 280.0   1st Qu.: 2.5634  
##  Median : 435.0   Median : 1166   Median : 409.0   Median : 3.5348  
##  Mean   : 537.9   Mean   : 1425   Mean   : 499.5   Mean   : 3.8707  
##  3rd Qu.: 647.0   3rd Qu.: 1725   3rd Qu.: 605.0   3rd Qu.: 4.7432  
##  Max.   :6445.0   Max.   :35682   Max.   :6082.0   Max.   :15.0001  
##  NA's   :207                                                        
##  ocean_proximity    median_house_value
##  Length:20640       Min.   : 14999    
##  Class :character   1st Qu.:119600    
##  Mode  :character   Median :179700    
##                     Mean   :206856    
##                     3rd Qu.:264725    
##                     Max.   :500001    
## 
boxplot(housing$longitude, main = "Longitude")

boxplot(housing$latitude, main = "Latitude")

boxplot(housing$housing_median_age, main = "Housing Median Age")

boxplot(housing$total_rooms, main = "Total Rooms")

boxplot(housing$total_bedrooms, main = "Total Bedrooms")

boxplot(housing$population, main = "Population")

boxplot(housing$households, main = "Households")

boxplot(housing$median_income, main = "Median Income")

boxplot(housing$median_house_value, main = "Median House Value")

model_of_the_transform <- preProcess(housing, method = c("center"))
print(model_of_the_transform)
## Created from 20433 samples and 10 variables
## 
## Pre-processing:
##   - centered (9)
##   - ignored (1)
housing_center_transform <- predict(model_of_the_transform, housing)

# AFTER
summary(housing_center_transform)
##    longitude        latitude      housing_median_age  total_rooms     
##  Min.   :-4.78   Min.   :-3.092   Min.   :-27.6395   Min.   :-2633.8  
##  1st Qu.:-2.23   1st Qu.:-1.702   1st Qu.:-10.6395   1st Qu.:-1188.0  
##  Median : 1.08   Median :-1.372   Median :  0.3605   Median : -508.8  
##  Mean   : 0.00   Mean   : 0.000   Mean   :  0.0000   Mean   :    0.0  
##  3rd Qu.: 1.56   3rd Qu.: 2.078   3rd Qu.:  8.3605   3rd Qu.:  512.2  
##  Max.   : 5.26   Max.   : 6.318   Max.   : 23.3605   Max.   :36684.2  
##                                                                       
##  total_bedrooms     population        households      median_income    
##  Min.   :-536.9   Min.   :-1422.5   Min.   :-498.54   Min.   :-3.3708  
##  1st Qu.:-241.9   1st Qu.: -638.5   1st Qu.:-219.54   1st Qu.:-1.3073  
##  Median :-102.9   Median : -259.5   Median : -90.54   Median :-0.3359  
##  Mean   :   0.0   Mean   :    0.0   Mean   :   0.00   Mean   : 0.0000  
##  3rd Qu.: 109.1   3rd Qu.:  299.5   3rd Qu.: 105.46   3rd Qu.: 0.8726  
##  Max.   :5907.1   Max.   :34256.5   Max.   :5582.46   Max.   :11.1294  
##  NA's   :207                                                           
##  ocean_proximity    median_house_value
##  Length:20640       Min.   :-191857   
##  Class :character   1st Qu.: -87256   
##  Mode  :character   Median : -27156   
##                     Mean   :      0   
##                     3rd Qu.:  57869   
##                     Max.   : 293145   
## 
boxplot(housing_center_transform$longitude, main = "Longitude")

boxplot(housing_center_transform$latitude, main = "Latitude")

boxplot(housing_center_transform$housing_median_age, main = "Housing Median Age")

boxplot(housing_center_transform$total_rooms, main = "Total Rooms")

boxplot(housing_center_transform$total_bedrooms, main = "Total Bedrooms")

boxplot(housing_center_transform$population, main = "Population")

boxplot(housing_center_transform$households, main = "Households")

boxplot(housing_center_transform$median_income, main = "Median Income")

boxplot(housing_center_transform$median_house_value, main = "Median House Value")

##### STEP 5. Apply a Standardize Basic Transform —-

####Standardize Basic Transform ----
summary(housing)
##    longitude         latitude     housing_median_age  total_rooms   
##  Min.   :-124.3   Min.   :32.54   Min.   : 1.00      Min.   :    2  
##  1st Qu.:-121.8   1st Qu.:33.93   1st Qu.:18.00      1st Qu.: 1448  
##  Median :-118.5   Median :34.26   Median :29.00      Median : 2127  
##  Mean   :-119.6   Mean   :35.63   Mean   :28.64      Mean   : 2636  
##  3rd Qu.:-118.0   3rd Qu.:37.71   3rd Qu.:37.00      3rd Qu.: 3148  
##  Max.   :-114.3   Max.   :41.95   Max.   :52.00      Max.   :39320  
##                                                                     
##  total_bedrooms     population      households     median_income    
##  Min.   :   1.0   Min.   :    3   Min.   :   1.0   Min.   : 0.4999  
##  1st Qu.: 296.0   1st Qu.:  787   1st Qu.: 280.0   1st Qu.: 2.5634  
##  Median : 435.0   Median : 1166   Median : 409.0   Median : 3.5348  
##  Mean   : 537.9   Mean   : 1425   Mean   : 499.5   Mean   : 3.8707  
##  3rd Qu.: 647.0   3rd Qu.: 1725   3rd Qu.: 605.0   3rd Qu.: 4.7432  
##  Max.   :6445.0   Max.   :35682   Max.   :6082.0   Max.   :15.0001  
##  NA's   :207                                                        
##  ocean_proximity    median_house_value
##  Length:20640       Min.   : 14999    
##  Class :character   1st Qu.:119600    
##  Mode  :character   Median :179700    
##                     Mean   :206856    
##                     3rd Qu.:264725    
##                     Max.   :500001    
## 
sapply(housing[, -9], sd)  # Assuming you want to exclude the ocean_proximity column
##          longitude           latitude housing_median_age        total_rooms 
##       2.003532e+00       2.135952e+00       1.258556e+01       2.181615e+03 
##     total_bedrooms         population         households      median_income 
##                 NA       1.132462e+03       3.823298e+02       1.899822e+00 
## median_house_value 
##       1.153956e+05
model_of_the_transform <- preProcess(housing,
                                     method = c("scale", "center"))
print(model_of_the_transform)
## Created from 20433 samples and 10 variables
## 
## Pre-processing:
##   - centered (9)
##   - ignored (1)
##   - scaled (9)
housing_standardize_transform <- predict(model_of_the_transform,
                                         housing)

# AFTER
summary(housing_standardize_transform)
##    longitude          latitude       housing_median_age  total_rooms     
##  Min.   :-2.3859   Min.   :-1.4475   Min.   :-2.19613   Min.   :-1.2073  
##  1st Qu.:-1.1132   1st Qu.:-0.7968   1st Qu.:-0.84537   1st Qu.:-0.5446  
##  Median : 0.5389   Median :-0.6423   Median : 0.02865   Median :-0.2332  
##  Mean   : 0.0000   Mean   : 0.0000   Mean   : 0.00000   Mean   : 0.0000  
##  3rd Qu.: 0.7785   3rd Qu.: 0.9729   3rd Qu.: 0.66429   3rd Qu.: 0.2348  
##  Max.   : 2.6252   Max.   : 2.9580   Max.   : 1.85614   Max.   :16.8152  
##                                                                          
##  total_bedrooms      population        households      median_income    
##  Min.   :-1.2741   Min.   :-1.2561   Min.   :-1.3040   Min.   :-1.7743  
##  1st Qu.:-0.5740   1st Qu.:-0.5638   1st Qu.:-0.5742   1st Qu.:-0.6881  
##  Median :-0.2441   Median :-0.2291   Median :-0.2368   Median :-0.1768  
##  Mean   : 0.0000   Mean   : 0.0000   Mean   : 0.0000   Mean   : 0.0000  
##  3rd Qu.: 0.2590   3rd Qu.: 0.2645   3rd Qu.: 0.2758   3rd Qu.: 0.4593  
##  Max.   :14.0184   Max.   :30.2496   Max.   :14.6012   Max.   : 5.8581  
##  NA's   :207                                                            
##  ocean_proximity    median_house_value
##  Length:20640       Min.   :-1.6626   
##  Class :character   1st Qu.:-0.7561   
##  Mode  :character   Median :-0.2353   
##                     Mean   : 0.0000   
##                     3rd Qu.: 0.5015   
##                     Max.   : 2.5403   
## 
sapply(housing_standardize_transform[, -9], sd) 
##          longitude           latitude housing_median_age        total_rooms 
##                  1                  1                  1                  1 
##     total_bedrooms         population         households      median_income 
##                 NA                  1                  1                  1 
## median_house_value 
##                  1

STEP 6. Apply a Normalize Data Transform —-

### The Normalize Transform on the Housing Dataset ----
summary(housing)
##    longitude         latitude     housing_median_age  total_rooms   
##  Min.   :-124.3   Min.   :32.54   Min.   : 1.00      Min.   :    2  
##  1st Qu.:-121.8   1st Qu.:33.93   1st Qu.:18.00      1st Qu.: 1448  
##  Median :-118.5   Median :34.26   Median :29.00      Median : 2127  
##  Mean   :-119.6   Mean   :35.63   Mean   :28.64      Mean   : 2636  
##  3rd Qu.:-118.0   3rd Qu.:37.71   3rd Qu.:37.00      3rd Qu.: 3148  
##  Max.   :-114.3   Max.   :41.95   Max.   :52.00      Max.   :39320  
##                                                                     
##  total_bedrooms     population      households     median_income    
##  Min.   :   1.0   Min.   :    3   Min.   :   1.0   Min.   : 0.4999  
##  1st Qu.: 296.0   1st Qu.:  787   1st Qu.: 280.0   1st Qu.: 2.5634  
##  Median : 435.0   Median : 1166   Median : 409.0   Median : 3.5348  
##  Mean   : 537.9   Mean   : 1425   Mean   : 499.5   Mean   : 3.8707  
##  3rd Qu.: 647.0   3rd Qu.: 1725   3rd Qu.: 605.0   3rd Qu.: 4.7432  
##  Max.   :6445.0   Max.   :35682   Max.   :6082.0   Max.   :15.0001  
##  NA's   :207                                                        
##  ocean_proximity    median_house_value
##  Length:20640       Min.   : 14999    
##  Class :character   1st Qu.:119600    
##  Mode  :character   Median :179700    
##                     Mean   :206856    
##                     3rd Qu.:264725    
##                     Max.   :500001    
## 
model_of_the_transform <- preProcess(housing, method = c("range"))
print(model_of_the_transform)
## Created from 20433 samples and 10 variables
## 
## Pre-processing:
##   - ignored (1)
##   - re-scaling to [0, 1] (9)
housing_normalize_transform <- predict(model_of_the_transform,
                                       housing)
summary(housing_normalize_transform)
##    longitude         latitude      housing_median_age  total_rooms     
##  Min.   :0.0000   Min.   :0.0000   Min.   :0.0000     Min.   :0.00000  
##  1st Qu.:0.2540   1st Qu.:0.1477   1st Qu.:0.3333     1st Qu.:0.03677  
##  Median :0.5837   Median :0.1828   Median :0.5490     Median :0.05405  
##  Mean   :0.4761   Mean   :0.3286   Mean   :0.5420     Mean   :0.06699  
##  3rd Qu.:0.6315   3rd Qu.:0.5494   3rd Qu.:0.7059     3rd Qu.:0.08001  
##  Max.   :1.0000   Max.   :1.0000   Max.   :1.0000     Max.   :1.00000  
##                                                                        
##  total_bedrooms      population        households      median_income   
##  Min.   :0.00000   Min.   :0.00000   Min.   :0.00000   Min.   :0.0000  
##  1st Qu.:0.04578   1st Qu.:0.02197   1st Qu.:0.04588   1st Qu.:0.1423  
##  Median :0.06735   Median :0.03260   Median :0.06709   Median :0.2093  
##  Mean   :0.08331   Mean   :0.03987   Mean   :0.08198   Mean   :0.2325  
##  3rd Qu.:0.10025   3rd Qu.:0.04826   3rd Qu.:0.09933   3rd Qu.:0.2926  
##  Max.   :1.00000   Max.   :1.00000   Max.   :1.00000   Max.   :1.0000  
##  NA's   :207                                                           
##  ocean_proximity    median_house_value
##  Length:20640       Min.   :0.0000    
##  Class :character   1st Qu.:0.2157    
##  Mode  :character   Median :0.3396    
##                     Mean   :0.3956    
##                     3rd Qu.:0.5149    
##                     Max.   :1.0000    
## 

STEP 7. Apply a Box-Cox Power Transform —-

### Box-Cox Power Transform on the Housing Dataset ----
# Summary of the housing dataset after the Standardize Basic Transform
summary(housing_standardize_transform)
##    longitude          latitude       housing_median_age  total_rooms     
##  Min.   :-2.3859   Min.   :-1.4475   Min.   :-2.19613   Min.   :-1.2073  
##  1st Qu.:-1.1132   1st Qu.:-0.7968   1st Qu.:-0.84537   1st Qu.:-0.5446  
##  Median : 0.5389   Median :-0.6423   Median : 0.02865   Median :-0.2332  
##  Mean   : 0.0000   Mean   : 0.0000   Mean   : 0.00000   Mean   : 0.0000  
##  3rd Qu.: 0.7785   3rd Qu.: 0.9729   3rd Qu.: 0.66429   3rd Qu.: 0.2348  
##  Max.   : 2.6252   Max.   : 2.9580   Max.   : 1.85614   Max.   :16.8152  
##                                                                          
##  total_bedrooms      population        households      median_income    
##  Min.   :-1.2741   Min.   :-1.2561   Min.   :-1.3040   Min.   :-1.7743  
##  1st Qu.:-0.5740   1st Qu.:-0.5638   1st Qu.:-0.5742   1st Qu.:-0.6881  
##  Median :-0.2441   Median :-0.2291   Median :-0.2368   Median :-0.1768  
##  Mean   : 0.0000   Mean   : 0.0000   Mean   : 0.0000   Mean   : 0.0000  
##  3rd Qu.: 0.2590   3rd Qu.: 0.2645   3rd Qu.: 0.2758   3rd Qu.: 0.4593  
##  Max.   :14.0184   Max.   :30.2496   Max.   :14.6012   Max.   : 5.8581  
##  NA's   :207                                                            
##  ocean_proximity    median_house_value
##  Length:20640       Min.   :-1.6626   
##  Class :character   1st Qu.:-0.7561   
##  Mode  :character   Median :-0.2353   
##                     Mean   : 0.0000   
##                     3rd Qu.: 0.5015   
##                     Max.   : 2.5403   
## 
# Calculate the skewness before the Box-Cox transform for a specific column (adjust column index as needed)
sapply(housing_standardize_transform[, 4], skewness, type = 2)
## total_rooms 
##    4.147343
sapply(housing_standardize_transform[, 4], sd)
## total_rooms 
##           1
# Apply Box-Cox Power Transform
model_of_the_transform <- preProcess(housing_standardize_transform, method = c("BoxCox"))
print(model_of_the_transform)
## Created from 20433 samples and 1 variables
## 
## Pre-processing:
##   - ignored (1)
housing_box_cox_transform <- predict(model_of_the_transform, housing_standardize_transform)

# Summary of the housing dataset after the Box-Cox Power Transform
summary(housing_box_cox_transform)
##    longitude          latitude       housing_median_age  total_rooms     
##  Min.   :-2.3859   Min.   :-1.4475   Min.   :-2.19613   Min.   :-1.2073  
##  1st Qu.:-1.1132   1st Qu.:-0.7968   1st Qu.:-0.84537   1st Qu.:-0.5446  
##  Median : 0.5389   Median :-0.6423   Median : 0.02865   Median :-0.2332  
##  Mean   : 0.0000   Mean   : 0.0000   Mean   : 0.00000   Mean   : 0.0000  
##  3rd Qu.: 0.7785   3rd Qu.: 0.9729   3rd Qu.: 0.66429   3rd Qu.: 0.2348  
##  Max.   : 2.6252   Max.   : 2.9580   Max.   : 1.85614   Max.   :16.8152  
##                                                                          
##  total_bedrooms      population        households      median_income    
##  Min.   :-1.2741   Min.   :-1.2561   Min.   :-1.3040   Min.   :-1.7743  
##  1st Qu.:-0.5740   1st Qu.:-0.5638   1st Qu.:-0.5742   1st Qu.:-0.6881  
##  Median :-0.2441   Median :-0.2291   Median :-0.2368   Median :-0.1768  
##  Mean   : 0.0000   Mean   : 0.0000   Mean   : 0.0000   Mean   : 0.0000  
##  3rd Qu.: 0.2590   3rd Qu.: 0.2645   3rd Qu.: 0.2758   3rd Qu.: 0.4593  
##  Max.   :14.0184   Max.   :30.2496   Max.   :14.6012   Max.   : 5.8581  
##  NA's   :207                                                            
##  ocean_proximity    median_house_value
##  Length:20640       Min.   :-1.6626   
##  Class :character   1st Qu.:-0.7561   
##  Mode  :character   Median :-0.2353   
##                     Mean   : 0.0000   
##                     3rd Qu.: 0.5015   
##                     Max.   : 2.5403   
## 
# Calculate the skewness and standard deviation after the Box-Cox transform for a specific column (adjust column index as needed)
sapply(housing_box_cox_transform[, 4], skewness, type = 2)
## total_rooms 
##    4.147343
sapply(housing_box_cox_transform[, 4], sd)
## total_rooms 
##           1
STEP 8. Apply a Yeo-Johnson Power Transform —-
####Yeo-Johnson Power Transform on the Housing Dataset ----
# BEFORE
summary(housing_standardize_transform)
##    longitude          latitude       housing_median_age  total_rooms     
##  Min.   :-2.3859   Min.   :-1.4475   Min.   :-2.19613   Min.   :-1.2073  
##  1st Qu.:-1.1132   1st Qu.:-0.7968   1st Qu.:-0.84537   1st Qu.:-0.5446  
##  Median : 0.5389   Median :-0.6423   Median : 0.02865   Median :-0.2332  
##  Mean   : 0.0000   Mean   : 0.0000   Mean   : 0.00000   Mean   : 0.0000  
##  3rd Qu.: 0.7785   3rd Qu.: 0.9729   3rd Qu.: 0.66429   3rd Qu.: 0.2348  
##  Max.   : 2.6252   Max.   : 2.9580   Max.   : 1.85614   Max.   :16.8152  
##                                                                          
##  total_bedrooms      population        households      median_income    
##  Min.   :-1.2741   Min.   :-1.2561   Min.   :-1.3040   Min.   :-1.7743  
##  1st Qu.:-0.5740   1st Qu.:-0.5638   1st Qu.:-0.5742   1st Qu.:-0.6881  
##  Median :-0.2441   Median :-0.2291   Median :-0.2368   Median :-0.1768  
##  Mean   : 0.0000   Mean   : 0.0000   Mean   : 0.0000   Mean   : 0.0000  
##  3rd Qu.: 0.2590   3rd Qu.: 0.2645   3rd Qu.: 0.2758   3rd Qu.: 0.4593  
##  Max.   :14.0184   Max.   :30.2496   Max.   :14.6012   Max.   : 5.8581  
##  NA's   :207                                                            
##  ocean_proximity    median_house_value
##  Length:20640       Min.   :-1.6626   
##  Class :character   1st Qu.:-0.7561   
##  Mode  :character   Median :-0.2353   
##                     Mean   : 0.0000   
##                     3rd Qu.: 0.5015   
##                     Max.   : 2.5403   
## 
# Calculate the skewness before the Yeo-Johnson transform for a specific column (adjust column index as needed)
sapply(housing_standardize_transform[, 4], skewness, type = 2)
## total_rooms 
##    4.147343
sapply(housing_standardize_transform[, 4], sd)
## total_rooms 
##           1
model_of_the_transform <- preProcess(housing_standardize_transform,
                                     method = c("YeoJohnson"))
print(model_of_the_transform)
## Created from 20433 samples and 10 variables
## 
## Pre-processing:
##   - ignored (1)
##   - Yeo-Johnson transformation (9)
## 
## Lambda estimates for Yeo-Johnson transformation:
## 1.39, 0.44, 0.96, -0.19, -0.14, -0.11, -0.09, 0.29, 0.28
housing_yeo_johnson_transform <- predict(model_of_the_transform, housing_standardize_transform)

# AFTER
summary(housing_yeo_johnson_transform)
##    longitude          latitude       housing_median_age  total_rooms     
##  Min.   :-1.8157   Min.   :-1.9469   Min.   :-2.26260   Min.   :-2.1252  
##  1st Qu.:-0.9498   1st Qu.:-0.9575   1st Qu.:-0.85775   1st Qu.:-0.7259  
##  Median : 0.5898   Median :-0.7484   Median : 0.02863   Median :-0.2659  
##  Mean   : 0.1416   Mean   :-0.2025   Mean   :-0.01550   Mean   :-0.2650  
##  3rd Qu.: 0.8809   3rd Qu.: 0.7926   3rd Qu.: 0.65646   3rd Qu.: 0.2068  
##  Max.   : 3.5774   Max.   : 1.8933   Max.   : 1.80784   Max.   : 2.2288  
##                                                                          
##  total_bedrooms      population        households      median_income    
##  Min.   :-2.2420   Min.   :-2.1684   Min.   :-2.2559   Min.   :-2.7710  
##  1st Qu.:-0.7660   1st Qu.:-0.7442   1st Qu.:-0.7561   1st Qu.:-0.8480  
##  Median :-0.2784   Median :-0.2586   Median :-0.2675   Median :-0.1878  
##  Mean   :-0.2710   Mean   :-0.2583   Mean   :-0.2636   Mean   :-0.2172  
##  3rd Qu.: 0.2267   3rd Qu.: 0.2316   3rd Qu.: 0.2410   3rd Qu.: 0.3991  
##  Max.   : 2.2591   Max.   : 2.8483   Max.   : 2.4434   Max.   : 2.5671  
##  NA's   :207                                                            
##  ocean_proximity    median_house_value
##  Length:20640       Min.   :-2.5528   
##  Class :character   1st Qu.:-0.9503   
##  Mode  :character   Median :-0.2549   
##                     Mean   :-0.2355   
##                     3rd Qu.: 0.4304   
##                     Max.   : 1.5163   
## 
# Calculate the skewness and standard deviation after the Yeo-Johnson transform for a specific column (adjust column index as needed)
sapply(housing_yeo_johnson_transform[, 4], skewness, type = 2)
##   total_rooms 
## -0.0006113658
sapply(housing_yeo_johnson_transform[, 4], sd)
## total_rooms 
##   0.6998448
# Principal Component Analysis (PCA) Linear Algebra Transform ----
### PCA for Dimensionality Reduction on the Housing Dataset ----
# The initial numeric variables are reduced to principal components
summary(housing)
##    longitude         latitude     housing_median_age  total_rooms   
##  Min.   :-124.3   Min.   :32.54   Min.   : 1.00      Min.   :    2  
##  1st Qu.:-121.8   1st Qu.:33.93   1st Qu.:18.00      1st Qu.: 1448  
##  Median :-118.5   Median :34.26   Median :29.00      Median : 2127  
##  Mean   :-119.6   Mean   :35.63   Mean   :28.64      Mean   : 2636  
##  3rd Qu.:-118.0   3rd Qu.:37.71   3rd Qu.:37.00      3rd Qu.: 3148  
##  Max.   :-114.3   Max.   :41.95   Max.   :52.00      Max.   :39320  
##                                                                     
##  total_bedrooms     population      households     median_income    
##  Min.   :   1.0   Min.   :    3   Min.   :   1.0   Min.   : 0.4999  
##  1st Qu.: 296.0   1st Qu.:  787   1st Qu.: 280.0   1st Qu.: 2.5634  
##  Median : 435.0   Median : 1166   Median : 409.0   Median : 3.5348  
##  Mean   : 537.9   Mean   : 1425   Mean   : 499.5   Mean   : 3.8707  
##  3rd Qu.: 647.0   3rd Qu.: 1725   3rd Qu.: 605.0   3rd Qu.: 4.7432  
##  Max.   :6445.0   Max.   :35682   Max.   :6082.0   Max.   :15.0001  
##  NA's   :207                                                        
##  ocean_proximity    median_house_value
##  Length:20640       Min.   : 14999    
##  Class :character   1st Qu.:119600    
##  Mode  :character   Median :179700    
##                     Mean   :206856    
##                     3rd Qu.:264725    
##                     Max.   :500001    
## 
model_of_the_transform <- preProcess(housing,
                                     method = c("scale", "center", "pca"))
print(model_of_the_transform)
## Created from 20433 samples and 10 variables
## 
## Pre-processing:
##   - centered (9)
##   - ignored (1)
##   - principal component signal extraction (9)
##   - scaled (9)
## 
## PCA needed 5 components to capture 95 percent of the variance
housing_pca_dr <- predict(model_of_the_transform, housing)

summary(housing_pca_dr)
##  ocean_proximity         PC1                PC2                PC3          
##  Length:20640       Min.   :-3.06324   Min.   :-3.24564   Min.   :-3.53755  
##  Class :character   1st Qu.:-1.14142   1st Qu.:-1.13869   1st Qu.:-0.92245  
##  Mode  :character   Median :-0.44655   Median :-0.55652   Median :-0.26644  
##                     Mean   :-0.00015   Mean   : 0.00068   Mean   : 0.00047  
##                     3rd Qu.: 0.57304   3rd Qu.: 1.32335   3rd Qu.: 0.68419  
##                     Max.   :32.06151   Max.   : 5.35189   Max.   : 6.30804  
##                     NA's   :207        NA's   :207        NA's   :207       
##       PC4                PC5          
##  Min.   :-5.87869   Min.   :-4.75865  
##  1st Qu.:-0.64830   1st Qu.:-0.34166  
##  Median :-0.05324   Median :-0.06017  
##  Mean   : 0.00064   Mean   : 0.00003  
##  3rd Qu.: 0.72022   3rd Qu.: 0.27805  
##  Max.   : 3.55313   Max.   : 3.07230  
##  NA's   :207        NA's   :207
dim(housing_pca_dr)
## [1] 20640     6

```