-
Notifications
You must be signed in to change notification settings - Fork 105
/
Copy pathclass-activity-6.Rmd
77 lines (51 loc) · 2.53 KB
/
class-activity-6.Rmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
---
title: 'HUDK4050: Class Activity 6'
author: "Charles Lang"
date: "10/23/2018"
output: html_document
---
# Data Management
```{r}
#Load data
DF1 <- read.csv("HUDK405019-clustering.csv", header = TRUE)
#Convert the index numbers of the data fram into the student names.
#Wrangle data using dplyr to include only the numerical values.
#Scale the data so that no variable has undue influence
DF2 <- scale(DF2)
```
# Find lattitudes & longitudes for cities
```{r}
#Unfortunately Google has restricted access to the Googple Maps API so the code below no longer works. Instead you have the lats and longs in your data.
#install.packages("ggmap")
#install.packages("rgdal")
#library(ggmap)
#library(tmaptools)
#Request lattitude and longitude from Google Maps API
#DF2 <- geocode(as.character(DF2$Q1_1), output = "latlon", source = "dsk")
```
Now we will run the K-means clustering algorithm we talked about in class.
1) The algorithm starts by randomly choosing some starting values
2) Associates all observations near to those values with them
3) Calculates the mean of those clusters of values
4) Selects the observation closest to the mean of the cluster
5) Re-associates all observations closest to this observation
6) Continues this process until the clusters are no longer changing
Notice that in this case we have 10 variables and in class we only had 2. It is impossible to vizualise this process with 10 variables.
Also, we need to choose the number of clusters we think are in the data. We will start with 4.
```{r}
fit <- kmeans(DF2, 1)
#We have created an object called "fit" that contains all the details of our clustering including which observations belong to each cluster.
#We can access the list of clusters by typing "fit$cluster", the top row corresponds to the original order the rows were in. Notice we have deleted some rows.
fit$cluster yay
#We can also attach these clusters to te original dataframe by using the "data.frame" command to create a new data frame called K4.
DF3 <- data.frame(DF2, fit$cluster)
#Have a look at the DF3 dataframe. Lets change the names of the variables to make it more convenient with the names() command.
names(DF3) <- c("1", "2", "3", "4", "5", "cluster") #c() stands for concatonate and it creates a vector of anything, in this case a vector of names.
```
# Visualize your clusters in ggplot
```{r}
#Create a scatterplot that plots location of each student and colors the points according to their cluster
```
# Can you group students from the classes data set in Assignment 2 using K-modes?
```{r}
```