library(readr)
mydata <-read_csv('clean data.csv')
## Rows: 54 Columns: 8
## ── Column specification ────────────────────────────────────────────────────────
## Delimiter: ","
## dbl (8): ID, Which Social Media Applications Do You Usually Use? Choose all ...
## 
## ℹ 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.

Importing data

In the following step, you will standardize your data(i.e., data with a mean of 0 and a standard deviation of 1). You can use the scale function from the R environment which is a generic function whose default method centers and/or scales the columns of a numeric matrix. ## Building distance function and ploting the trees (dendrograms) Hierarchical clustering (using the function hclust) is an informative way to visualize the data. We will see if we could discover subgroups among the variables or among the observations.

use = scale(mydata[,-c(1)], center = TRUE, scale = TRUE)
dist = dist(use)
d <- dist(as.matrix(dist)) # find distance matrix
seg.hclust <- hclust(d) # apply hirarchical clustering
library(ggplot2) # needs no introduction
plot(seg.hclust)

## Identifying clustering memberships for each cluster Imagine if your goal is to find some profitable customers to target. Now you will be able to see the number of customers using this algorithm.

groups.7 = cutree(seg.hclust,7)
table(groups.7) #A good first step is to use the table function to see how
## groups.7
##  1  2  3  4  5  6  7 
## 10  5  4  3 28  3  1
# many observations are in each cluster
#In the following step, we will find the members in each cluster or group.
mydata$ID[groups.7 == 1]
##  [1]  1  5  9 12 19 20 32 36 48 54
mydata$ID[groups.7 == 2]
## [1]  2 10 31 34 43
mydata$ID[groups.7 == 3]
## [1]  3  8 37 49
mydata$ID[groups.7 == 4]
## [1]  4  6 41
mydata$ID[groups.7 == 5]
##  [1]  7 11 13 14 15 16 17 18 21 22 25 26 27 28 29 30 35 38 39 40 42 44 45 47 50
## [26] 51 52 53
mydata$ID[groups.7 == 6]
## [1] 23 24 46
mydata$ID[groups.7 == 7]
## [1] 33

Identifying common features of each cluster using the aggregate

function

#?aggregate
aggregate(mydata,list(groups.7),median)
##   Group.1   ID
## 1       1 19.5
## 2       2 31.0
## 3       3 22.5
## 4       4  6.0
## 5       5 28.5
## 6       6 24.0
## 7       7 33.0
##   Which Social Media Applications Do You Usually Use? Choose all that apply.
## 1                                                                        3.0
## 2                                                                        1.0
## 3                                                                        4.5
## 4                                                                        3.0
## 5                                                                        2.0
## 6                                                                        3.0
## 7                                                                        1.0
##   What Type of Advertisements Do You See on These Apps? Choose all that apply.
## 1                                                                          4.5
## 2                                                                          1.0
## 3                                                                          4.5
## 4                                                                          4.0
## 5                                                                          3.5
## 6                                                                          4.0
## 7                                                                          3.0
##   Do You Ever See Ads for Financial Institutions on Social Media?
## 1                                                             1.5
## 2                                                             2.0
## 3                                                             2.0
## 4                                                             2.0
## 5                                                             2.0
## 6                                                             1.0
## 7                                                             1.0
##   What Types of Methods Have You Used for Budgeting?
## 1                                                  1
## 2                                                  1
## 3                                                  1
## 4                                                  1
## 5                                                  1
## 6                                                  1
## 7                                                 11
##   How Would You Invest/Spend Your First Paycheck?
## 1                                               5
## 2                                               3
## 3                                               4
## 4                                               4
## 5                                               2
## 6                                               7
## 7                                               0
##   Who Would You Reach Out To For Financial Advice?
## 1                                                2
## 2                                                1
## 3                                                3
## 4                                                1
## 5                                                1
## 6                                                3
## 7                                                2
##   How do you prefer to communicate?
## 1                               3.0
## 2                               1.0
## 3                               1.5
## 4                               6.0
## 5                               2.0
## 6                               2.0
## 7                               6.0
aggregate(mydata,list(groups.7),mean)
##   Group.1       ID
## 1       1 23.60000
## 2       2 24.00000
## 3       3 24.25000
## 4       4 17.00000
## 5       5 30.53571
## 6       6 31.00000
## 7       7 33.00000
##   Which Social Media Applications Do You Usually Use? Choose all that apply.
## 1                                                                   2.500000
## 2                                                                   1.200000
## 3                                                                   4.250000
## 4                                                                   3.000000
## 5                                                                   2.392857
## 6                                                                   3.333333
## 7                                                                   1.000000
##   What Type of Advertisements Do You See on These Apps? Choose all that apply.
## 1                                                                     4.500000
## 2                                                                     1.200000
## 3                                                                     4.750000
## 4                                                                     4.000000
## 5                                                                     3.535714
## 6                                                                     4.666667
## 7                                                                     3.000000
##   Do You Ever See Ads for Financial Institutions on Social Media?
## 1                                                        1.500000
## 2                                                        1.800000
## 3                                                        1.750000
## 4                                                        1.666667
## 5                                                        1.678571
## 6                                                        1.000000
## 7                                                        1.000000
##   What Types of Methods Have You Used for Budgeting?
## 1                                           1.100000
## 2                                           1.000000
## 3                                           1.000000
## 4                                           1.000000
## 5                                           1.285714
## 6                                           1.000000
## 7                                          11.000000
##   How Would You Invest/Spend Your First Paycheck?
## 1                                        4.500000
## 2                                        2.800000
## 3                                        3.750000
## 4                                        4.666667
## 5                                        2.142857
## 6                                        7.000000
## 7                                        0.000000
##   Who Would You Reach Out To For Financial Advice?
## 1                                         2.000000
## 2                                         1.000000
## 3                                         2.750000
## 4                                         1.333333
## 5                                         1.285714
## 6                                         2.666667
## 7                                         2.000000
##   How do you prefer to communicate?
## 1                          2.900000
## 2                          1.400000
## 3                          1.500000
## 4                          5.666667
## 5                          2.142857
## 6                          2.666667
## 7                          6.000000
aggregate(mydata[,-1],list(groups.7),median)
##   Group.1
## 1       1
## 2       2
## 3       3
## 4       4
## 5       5
## 6       6
## 7       7
##   Which Social Media Applications Do You Usually Use? Choose all that apply.
## 1                                                                        3.0
## 2                                                                        1.0
## 3                                                                        4.5
## 4                                                                        3.0
## 5                                                                        2.0
## 6                                                                        3.0
## 7                                                                        1.0
##   What Type of Advertisements Do You See on These Apps? Choose all that apply.
## 1                                                                          4.5
## 2                                                                          1.0
## 3                                                                          4.5
## 4                                                                          4.0
## 5                                                                          3.5
## 6                                                                          4.0
## 7                                                                          3.0
##   Do You Ever See Ads for Financial Institutions on Social Media?
## 1                                                             1.5
## 2                                                             2.0
## 3                                                             2.0
## 4                                                             2.0
## 5                                                             2.0
## 6                                                             1.0
## 7                                                             1.0
##   What Types of Methods Have You Used for Budgeting?
## 1                                                  1
## 2                                                  1
## 3                                                  1
## 4                                                  1
## 5                                                  1
## 6                                                  1
## 7                                                 11
##   How Would You Invest/Spend Your First Paycheck?
## 1                                               5
## 2                                               3
## 3                                               4
## 4                                               4
## 5                                               2
## 6                                               7
## 7                                               0
##   Who Would You Reach Out To For Financial Advice?
## 1                                                2
## 2                                                1
## 3                                                3
## 4                                                1
## 5                                                1
## 6                                                3
## 7                                                2
##   How do you prefer to communicate?
## 1                               3.0
## 2                               1.0
## 3                               1.5
## 4                               6.0
## 5                               2.0
## 6                               2.0
## 7                               6.0
aggregate(mydata[,-1],list(groups.7),mean)
##   Group.1
## 1       1
## 2       2
## 3       3
## 4       4
## 5       5
## 6       6
## 7       7
##   Which Social Media Applications Do You Usually Use? Choose all that apply.
## 1                                                                   2.500000
## 2                                                                   1.200000
## 3                                                                   4.250000
## 4                                                                   3.000000
## 5                                                                   2.392857
## 6                                                                   3.333333
## 7                                                                   1.000000
##   What Type of Advertisements Do You See on These Apps? Choose all that apply.
## 1                                                                     4.500000
## 2                                                                     1.200000
## 3                                                                     4.750000
## 4                                                                     4.000000
## 5                                                                     3.535714
## 6                                                                     4.666667
## 7                                                                     3.000000
##   Do You Ever See Ads for Financial Institutions on Social Media?
## 1                                                        1.500000
## 2                                                        1.800000
## 3                                                        1.750000
## 4                                                        1.666667
## 5                                                        1.678571
## 6                                                        1.000000
## 7                                                        1.000000
##   What Types of Methods Have You Used for Budgeting?
## 1                                           1.100000
## 2                                           1.000000
## 3                                           1.000000
## 4                                           1.000000
## 5                                           1.285714
## 6                                           1.000000
## 7                                          11.000000
##   How Would You Invest/Spend Your First Paycheck?
## 1                                        4.500000
## 2                                        2.800000
## 3                                        3.750000
## 4                                        4.666667
## 5                                        2.142857
## 6                                        7.000000
## 7                                        0.000000
##   Who Would You Reach Out To For Financial Advice?
## 1                                         2.000000
## 2                                         1.000000
## 3                                         2.750000
## 4                                         1.333333
## 5                                         1.285714
## 6                                         2.666667
## 7                                         2.000000
##   How do you prefer to communicate?
## 1                          2.900000
## 2                          1.400000
## 3                          1.500000
## 4                          5.666667
## 5                          2.142857
## 6                          2.666667
## 7                          6.000000
cluster_means <- aggregate(mydata[,-1],list(groups.7),mean)

Exporting cluster analysis results into excel from R Studio Cloud

write.csv(groups.7, "clusterID.csv")
write.csv(cluster_means, "cluster_means.csv")

Downloading your solutions mannually

First, select the files (“clusterID.csv” & “cluster_means.csv”) and put a checkmark before each file. Second, click the gear icon on the right side of your pane and export the data. ## Finding means or medians of each variable (factor) for each cluster Imagine if your goal is to find some profitable customers to target. Now using the mean function or the median function, you will be able to see the characteristics of each sub-group. Now it is time to use your domain expertise. ### Discussion Questions for you (about 20 words per question) 1. How many observations do we have in each cluster? Answer: Your answer here: 2. We can look at the medians (or means) for the variables in each cluster. Why is this important? Answer: Your answer here: 3. Do you think if mean or median should be used when it comes to analyzing the differences among different clusters? Why? Answer: Your answer here: 4. Now we need to understand the common characteristics of each cluster. Our goal is to build targeting strategy using the profiles of each cluster. What summary measures of each cluster are appropriate in a descriptive sense. Answer: Your answer here: 5. Any major differences between K-means clustering (https://rpubs.com/utjimmyx/kmeans) and Hierarchical clustering? Which one do you like better? Why? You may refer to the assigned readings. 6. Do a keyword search using “cluster analysis.” How many relevant job titles are there? Answer: Your answer here: ### Advanced Questions (optional but highly recommended) O. The aggregate function is well suited for this task. Should we use mydata or mydata[,-1] along with the aggregate function? Why? Hint: see the results on my tutorial. ## ################################################################# ## Principal Component Analysis (PCA) ## ## ########################################################################## #### ## Intro Principal Component Analysis (PCA) involves the process of understanding different features in a dataset and can be used in conjunction with cluster analysis. PCA is also a popular machine learning algorithm used for feature selection. Imagine if you have more than 100 features or factors. It is useful to select the most important features for further analysis. The basic idea when using PCA as a tool for feature selection is to select variables according to the magnitude (from largest to smallest in absolute values) of their coefficients (loadings).

#install.packages('dplyr')
library(dplyr) # sane data manipulation
## 
## 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
library(tidyr) # sane data munging
library(ggplot2) # needs no introduction
library(ggfortify) # super-helpful for plotting non-"standard" stats
objects
## function (name, pos = -1L, envir = as.environment(pos), all.names = FALSE, 
##     pattern, sorted = TRUE) 
## {
##     if (!missing(name)) {
##         pos <- tryCatch(name, error = function(e) e)
##         if (inherits(pos, "error")) {
##             name <- substitute(name)
##             if (!is.character(name)) 
##                 name <- deparse(name)
##             warning(gettextf("%s converted to character string", 
##                 sQuote(name)), domain = NA)
##             pos <- name
##         }
##     }
##     all.names <- .Internal(ls(envir, all.names, sorted))
##     if (!missing(pattern)) {
##         if ((ll <- length(grep("[", pattern, fixed = TRUE))) && 
##             ll != length(grep("]", pattern, fixed = TRUE))) {
##             if (pattern == "[") {
##                 pattern <- "\\["
##                 warning("replaced regular expression pattern '[' by  '\\\\['")
##             }
##             else if (length(grep("[^\\\\]\\[<-", pattern))) {
##                 pattern <- sub("\\[<-", "\\\\\\[<-", pattern)
##                 warning("replaced '[<-' by '\\\\[<-' in regular expression pattern")
##             }
##         }
##         grep(pattern, all.names, value = TRUE)
##     }
##     else all.names
## }
## <bytecode: 0x620b596ff6c0>
## <environment: namespace:base>
#identifying your working directory
getwd() #confirm your working directory is accurate
## [1] "/cloud/project"
library(readr)
## mydata <-read_csv('Segmentation.csv')
mydata <-read_csv('clean data.csv')
## Rows: 54 Columns: 8
## ── Column specification ────────────────────────────────────────────────────────
## Delimiter: ","
## dbl (8): ID, Which Social Media Applications Do You Usually Use? Choose all ...
## 
## ℹ 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.
# read csv file #This allows you to read the data from my Github site.
#Open the data. Note that some students will see an Excel option in
"Import Dataset";
## [1] "Import Dataset"
#those that do not will need to save the original data as a csv and import that as a text file.
#rm(list = ls()) #used to clean your working environment
fit <- kmeans(mydata[,-1], 7, iter.max=1000)
#exclude the first column since it is "id" instead of a factor #or variable.
#3 means you want to have 3 clusters
table(fit$cluster)
## 
##  1  2  3  4  5  6  7 
##  9  1  8 13  8  6  9
barplot(table(fit$cluster), col="#336699") #plot

pca <- prcomp(mydata[,-1], scale=TRUE) #principle component analysis
pca_data <- mutate(fortify(pca), col=fit$cluster)
#We want to examine the cluster memberships for each #observation - see last column
ggplot(pca_data) + geom_point(aes(x=PC1, y=PC2, fill=factor(col)),
size=7, col="#7f7f7f", shape=21) + theme_bw(base_family="Helvetica")

autoplot(fit, data=mydata[,-1], frame=TRUE, frame.type='norm')
## Too few points to calculate an ellipse

names(pca)
## [1] "sdev"     "rotation" "center"   "scale"    "x"
pca$center
##   Which Social Media Applications Do You Usually Use? Choose all that apply. 
##                                                                     2.500000 
## What Type of Advertisements Do You See on These Apps? Choose all that apply. 
##                                                                     3.666667 
##              Do You Ever See Ads for Financial Institutions on Social Media? 
##                                                                     1.611111 
##                           What Types of Methods Have You Used for Budgeting? 
##                                                                     1.351852 
##                              How Would You Invest/Spend Your First Paycheck? 
##                                                                     3.129630 
##                             Who Would You Reach Out To For Financial Advice? 
##                                                                     1.592593 
##                                            How do you prefer to communicate? 
##                                                                     2.462963
pca$scale
##   Which Social Media Applications Do You Usually Use? Choose all that apply. 
##                                                                    1.0595478 
## What Type of Advertisements Do You See on These Apps? Choose all that apply. 
##                                                                    1.5295825 
##              Do You Ever See Ads for Financial Institutions on Social Media? 
##                                                                    0.4920756 
##                           What Types of Methods Have You Used for Budgeting? 
##                                                                    1.4163121 
##                              How Would You Invest/Spend Your First Paycheck? 
##                                                                    1.7051121 
##                             Who Would You Reach Out To For Financial Advice? 
##                                                                    0.6873114 
##                                            How do you prefer to communicate? 
##                                                                    1.2843464
pca$rotation
##                                                                                     PC1
## Which Social Media Applications Do You Usually Use? Choose all that apply.   -0.4994521
## What Type of Advertisements Do You See on These Apps? Choose all that apply. -0.4487136
## Do You Ever See Ads for Financial Institutions on Social Media?               0.1448520
## What Types of Methods Have You Used for Budgeting?                            0.1574349
## How Would You Invest/Spend Your First Paycheck?                              -0.4746336
## Who Would You Reach Out To For Financial Advice?                             -0.5163964
## How do you prefer to communicate?                                            -0.1072088
##                                                                                      PC2
## Which Social Media Applications Do You Usually Use? Choose all that apply.    0.24060418
## What Type of Advertisements Do You See on These Apps? Choose all that apply. -0.06119714
## Do You Ever See Ads for Financial Institutions on Social Media?               0.47384403
## What Types of Methods Have You Used for Budgeting?                           -0.59740541
## How Would You Invest/Spend Your First Paycheck?                               0.05907917
## Who Would You Reach Out To For Financial Advice?                             -0.16443830
## How do you prefer to communicate?                                            -0.57132551
##                                                                                       PC3
## Which Social Media Applications Do You Usually Use? Choose all that apply.   -0.386903594
## What Type of Advertisements Do You See on These Apps? Choose all that apply. -0.303530506
## Do You Ever See Ads for Financial Institutions on Social Media?              -0.628659970
## What Types of Methods Have You Used for Budgeting?                           -0.441103302
## How Would You Invest/Spend Your First Paycheck?                               0.380220984
## Who Would You Reach Out To For Financial Advice?                              0.009642222
## How do you prefer to communicate?                                            -0.154040228
##                                                                                      PC4
## Which Social Media Applications Do You Usually Use? Choose all that apply.   -0.12107605
## What Type of Advertisements Do You See on These Apps? Choose all that apply. -0.02461163
## Do You Ever See Ads for Financial Institutions on Social Media?               0.36784569
## What Types of Methods Have You Used for Budgeting?                           -0.15754107
## How Would You Invest/Spend Your First Paycheck?                               0.53585126
## Who Would You Reach Out To For Financial Advice?                             -0.42316218
## How do you prefer to communicate?                                             0.59866720
##                                                                                      PC5
## Which Social Media Applications Do You Usually Use? Choose all that apply.    0.19352828
## What Type of Advertisements Do You See on These Apps? Choose all that apply. -0.78980189
## Do You Ever See Ads for Financial Institutions on Social Media?               0.23675637
## What Types of Methods Have You Used for Budgeting?                            0.22654211
## How Would You Invest/Spend Your First Paycheck?                               0.22019678
## Who Would You Reach Out To For Financial Advice?                              0.42690662
## How do you prefer to communicate?                                             0.02547528
##                                                                                     PC6
## Which Social Media Applications Do You Usually Use? Choose all that apply.    0.5906881
## What Type of Advertisements Do You See on These Apps? Choose all that apply. -0.2779098
## Do You Ever See Ads for Financial Institutions on Social Media?              -0.3268155
## What Types of Methods Have You Used for Budgeting?                           -0.3304196
## How Would You Invest/Spend Your First Paycheck?                              -0.3817667
## Who Would You Reach Out To For Financial Advice?                             -0.2514490
## How do you prefer to communicate?                                             0.3858703
##                                                                                      PC7
## Which Social Media Applications Do You Usually Use? Choose all that apply.   -0.37674645
## What Type of Advertisements Do You See on These Apps? Choose all that apply.  0.03396604
## Do You Ever See Ads for Financial Institutions on Social Media?               0.24719214
## What Types of Methods Have You Used for Budgeting?                           -0.48829425
## How Would You Invest/Spend Your First Paycheck?                              -0.38117663
## Who Would You Reach Out To For Financial Advice?                              0.53071632
## How do you prefer to communicate?                                             0.36113399
dim(pca$x)
## [1] 54  7
biplot(pca, scale=0)

pca$rotation=-pca$rotation
pca$x=-pca$x
biplot(pca, scale=0)

pca$sdev
## [1] 1.4202601 1.2687649 0.9582224 0.9281452 0.8616770 0.7121238 0.5863837
pca.var=pca$sdev^2
pca.var
## [1] 2.0171386 1.6097643 0.9181901 0.8614536 0.7424872 0.5071203 0.3438458
pve=pca.var/sum(pca.var)
pve
## [1] 0.28816266 0.22996634 0.13117001 0.12306480 0.10606960 0.07244576 0.04912083
plot(pve, xlab="Principal Component", ylab="Proportion of Variance
Explained", ylim=c(0,1),type='b')

plot(cumsum(pve), xlab="Principal Component", ylab="Cumulative Proportion
of Variance Explained", ylim=c(0,1),type='b')

write.csv(pca_data, "pca_data.csv")
#save your cluster solutions in the working directory
#We want to examine the cluster memberships for each observation - see last column of pca_data