<p><div><div><div><div data-show-faces="false" data-height="21" data-width="100" data-layout="button_count" data-send="true" data-href="https://www.r-bloggers.com/exploring-clustering-and-mapping-torontos-crimes/"></div></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="https://datascienceplus.com/exploring-clustering-and-mapping-torontos-crimes/"> R Programming – DataScience+</a></strong>, and kindly contributed to <a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers)</a> </div>
<h2>Motivation</h2>
<p>I have had a lot of fun exploring The US cities’ Crime data via their Open Data portals. Because Toronto’s crime data was simply not available.</p>
<p>Not until the summer of this year, Toronto police launch a public safety data portal to increase transparency between the public and officers. I recently have had the chance to explore Toronto’s crimes via <a rel="nofollow" href="http://data.torontopolice.on.ca/pages/open-data" target="_blank">Toronto Police Service Public Safety Data Portal</a>. I am particularly interested in <a rel="nofollow" href="http://data.torontopolice.on.ca/datasets?t=MCI" target="_blank">Major Crime Indicators (MCI) 2016</a> which contains a tabular list of 32, 612 reports in 2016 (The only year that the data were made available).</p>
<p><a rel="nofollow" href="https://i1.wp.com/datascienceplus.com/wp-content/uploads/2017/10/2017-10-28.png?ssl=1" target="_blank"><img sizes="(max-width: 490px) 100vw, 490px" src="https://i2.wp.com/datascienceplus.com/wp-content/uploads/2017/10/2017-10-28-490x243.png?w=450&ssl=1" alt="" class="wp-image-9252" data-recalc-dims="1"></a></p>
<p>Let’s take a look at the data using R and see if there’s anything interesting.</p>
<pre>
library(ggplot2)
library(ggthemes)
library(dplyr)
library(viridis)
library(tidyr)
library(cluster)
library(ggmap)
library(maps)
</pre>
<p>After a little bit of exploration, I found that there were many duplicated event_unique_id. Let’s drop them.</p>
<pre>
toronto &lt;- read.csv('toronto_crime.csv')
toronto &lt;- subset(toronto, !duplicated(toronto$event_unique_id))
unique(toronto$occurrenceyear)
unique(toronto$reportedyear)
<em>> unique(toronto$occurrenceyear)
[1] 2016 2015 2014 2012 2010 2013 2011 2003 2007 2008 2006 2002 2001 NA 2005
[16] 2009 2000
> unique(toronto$reportedyear)
[1] 2016
</em>
</pre>
<p>Find anything interesting? The occurrence year ranged from 2000 to 2016, but report year is only 2016. This means people came to police to report incidents happened 16 years ago. Let’s have a look how many late reported incidents in our data.</p>
<pre>
year_group &lt;- group_by(toronto, occurrenceyear)
crime_by_year &lt;- summarise(year_group,
                          n = n())
crime_by_year
<em># A tibble: 17 x 2
occurrenceyear n
1 2000 2
2 2001 2
3 2002 3
4 2003 2
5 2005 1
6 2006 1
7 2007 5
8 2008 1
9 2009 1
10 2010 10
11 2011 3
12 2012 8
13 2013 21
14 2014 37
15 2015 341
16 2016 27705
17 NA 4
</em>
</pre>
<p>2 incidents occurred in 2000, 2 occurred in 2001 and so on. The vast majority of occurrences happened in 2016. So we are going to keep 2016 only. And I am also removing all the columns we do not need and four rows with missing values.</p>
<pre>
drops &lt;- c(&quot;X&quot;, &quot;Y&quot;, &quot;Index_&quot;, &quot;ucr_code&quot;, &quot;ucr_ext&quot;, &quot;reporteddate&quot;, &quot;reportedmonth&quot;, &quot;reportedday&quot;, &quot;reporteddayofyear&quot;, &quot;reporteddayofweek&quot;, &quot;reportedhour&quot;, &quot;occurrencedayofyear&quot;, &quot;reportedyear&quot;, &quot;Division&quot;, &quot;Hood_ID&quot;, &quot;FID&quot;)
toronto &lt;- toronto[, !(names(toronto) %in% drops)]
toronto &lt;- toronto[toronto$occurrenceyear == 2016, ]
toronto &lt;- toronto[complete.cases(toronto), ]
</pre>
<h2>Explore</h2>
<h3>What are the major crimes in 2016?</h3>
<pre>
indicator_group &lt;- group_by(toronto, MCI)
crime_by_indicator &lt;- summarise(indicator_group, n=n())
crime_by_indicator &lt;- crime_by_indicator[order(crime_by_indicator$n, decreasing = TRUE),]
ggplot(aes(x = reorder(MCI, n), y = n), data = crime_by_indicator) +
  geom_bar(stat = 'identity', width = 0.5) +
  geom_text(aes(label = n), stat = 'identity', data = crime_by_indicator, hjust = -0.1, size = 3.5) +
  coord_flip() +
  xlab('Major Crime Indicators') +
  ylab('Number of Occurrences') +
  ggtitle('Major Crime Indicators Toronto 2016') +
  theme_bw() +
  theme(plot.title = element_text(size = 16),
        axis.title = element_text(size = 12, face = &quot;bold&quot;))
</pre>
<p>Gives this plot:<br>
<a rel="nofollow" href="https://i1.wp.com/datascienceplus.com/wp-content/uploads/2017/10/toronto_1.png?ssl=1" target="_blank"><img sizes="(max-width: 490px) 100vw, 490px" src="https://i0.wp.com/datascienceplus.com/wp-content/uploads/2017/10/toronto_1-490x227.png?w=450&ssl=1" alt="" class="wp-image-9253" data-recalc-dims="1"></a><br>
Assault is the most prevalent form of violent crime in Toronto. What is assault? In criminal and civil law, assault is an attempt to initiate harmful or offensive contact with a person, or a threat to do so.</p>
<h3>What are the different types of assault? Which type is the worst?</h3>
<pre>
assault &lt;- toronto[toronto$MCI == 'Assault', ]
assault_group &lt;- group_by(assault, offence)
assault_by_offence &lt;- summarise(assault_group, n=n())
assault_by_offence &lt;- assault_by_offence[order(assault_by_offence$n, decreasing = TRUE), ]
ggplot(aes(x = reorder(offence, n), y = n), data = assault_by_offence) +
  geom_bar(stat = 'identity', width = 0.6) +
  geom_text(aes(label = n), stat = 'identity', data = assault_by_offence, hjust = -0.1, size = 3) +
  coord_flip() +
  xlab('Types of Assault') +
  ylab('Number of Occurrences') +
  ggtitle('Assault Crime Toronto 2016') +
  theme_bw() +
  theme(plot.title = element_text(size = 16),
        axis.title = element_text(size = 12, face = &quot;bold&quot;))
</pre>
<p>Gives this plot:<br>
<a rel="nofollow" href="https://i1.wp.com/datascienceplus.com/wp-content/uploads/2017/10/toronto_2.png?ssl=1" target="_blank"><img sizes="(max-width: 490px) 100vw, 490px" src="https://i1.wp.com/datascienceplus.com/wp-content/uploads/2017/10/toronto_2-490x227.png?w=450&ssl=1" alt="" class="wp-image-9254" data-recalc-dims="1"></a><br>
Not much information here, the top assault category is … assault. I eventually learned different types of assault through Attorneys.com.</p>
<h3>Let’s look at the top offences then</h3>
<pre>
offence_group &lt;- group_by(toronto, offence)
crime_by_offence &lt;- summarise(offence_group, n=n())
crime_by_offence &lt;- crime_by_offence[order(crime_by_offence$n, decreasing = TRUE), ]
ggplot(aes(x = reorder(offence, n), y = n), data = crime_by_offence) +
  geom_bar(stat = 'identity', width = 0.7) +
  geom_text(aes(label = n), stat = 'identity', data = crime_by_offence, hjust = -0.1, size = 2) +
  coord_flip() +
  xlab('Types of Offence') +
  ylab('Number of Occurrences') +
  ggtitle('Offence Types Toronto 2016') +
  theme_bw() +
  theme(plot.title = element_text(size = 16),
        axis.title = element_text(size = 12, face = &quot;bold&quot;))
</pre>
<p>Gives this plot:<br>
<a rel="nofollow" href="https://i1.wp.com/datascienceplus.com/wp-content/uploads/2017/10/toronto_3.png?ssl=1" target="_blank"><img sizes="(max-width: 490px) 100vw, 490px" src="https://i1.wp.com/datascienceplus.com/wp-content/uploads/2017/10/toronto_3-490x227.png?w=450&ssl=1" alt="" class="wp-image-9255" data-recalc-dims="1"></a><br>
Assault being the most common offence followed by Break and Enter. According to Wikibooks, the most typical form of break and enter is a break into a commercial or private residence in order to steal property. This indicates that break and enter more likely to occur when there is no one at home or office.</p>
<h3>How about crime by time of the day?</h3>
<pre>
hour_group &lt;- group_by(toronto, occurrencehour)
crime_hour &lt;- summarise(hour_group, n=n())
ggplot(aes(x=occurrencehour, y=n), data = crime_hour) + geom_line(size = 2.5, alpha = 0.7, color = &quot;mediumseagreen&quot;, group=1) + 
  geom_point(size = 0.5) + 
  ggtitle('Total Crimes by Hour of Day in Toronto 2016') +
  ylab('Number of Occurrences') +
  xlab('Hour(24-hour clock)') +
  theme_bw() +
  theme(plot.title = element_text(size = 16),
        axis.title = element_text(size = 12, face = &quot;bold&quot;))
</pre>
<p>Gives this plot:<br>
<a rel="nofollow" href="https://i2.wp.com/datascienceplus.com/wp-content/uploads/2017/10/toronto_14.png?ssl=1" target="_blank"><img sizes="(max-width: 490px) 100vw, 490px" src="https://i2.wp.com/datascienceplus.com/wp-content/uploads/2017/10/toronto_14-490x227.png?w=450&ssl=1" alt="" class="wp-image-9256" data-recalc-dims="1"></a><br>
The worst hour is around the midnight, another peak time is around the noon, then again at around 8pm.</p>
<h3>Okay, but what types of crime are most frequent at each hour?</h3>
<pre>
hour_crime_group &lt;- group_by(toronto, occurrencehour, MCI)
hour_crime &lt;- summarise(hour_crime_group, n=n())
ggplot(aes(x=occurrencehour, y=n, color=MCI), data =hour_crime) + 
  geom_line(size=1.5) + 
  ggtitle('Crime Types by Hour of Day in Toronto 2016') +
  ylab('Number of Occurrences') +
  xlab('Hour(24-hour clock)') +
  theme_bw() +
  theme(plot.title = element_text(size = 16),
        axis.title = element_text(size = 12, face = &quot;bold&quot;))
</pre>
<p>Gives this plot:<br>
<a rel="nofollow" href="https://i2.wp.com/datascienceplus.com/wp-content/uploads/2017/10/toronto_15.png?ssl=1" target="_blank"><img sizes="(max-width: 490px) 100vw, 490px" src="https://i0.wp.com/datascienceplus.com/wp-content/uploads/2017/10/toronto_15-490x227.png?w=450&ssl=1" alt="" class="wp-image-9257" data-recalc-dims="1"></a><br>
Assaults are the top crimes almost all the time, they happened more often from the late mornings till nights than the early mornings. On the other hand, break and enter happened more often in the mornings and at around the midnight (when no one at home or office) . Robberies and auto thefts are more likely to happen in the late evenings till the nights. They all make sense.</p>
<h3>Where are those crimes most likely to occur in Toronto?</h3>
<pre>
location_group &lt;- group_by(toronto, Neighbourhood)
crime_by_location &lt;- summarise(location_group, n=n())
crime_by_location &lt;- crime_by_location[order(crime_by_location$n, decreasing = TRUE), ]
crime_by_location_top20 &lt;- head(crime_by_location, 20)
ggplot(aes(x = reorder(Neighbourhood, n), y = n), data = crime_by_location_top20) +
  geom_bar(stat = 'identity', width = 0.6) +
  geom_text(aes(label = n), stat = 'identity', data = crime_by_location_top20, hjust = -0.1, size = 3) +
  coord_flip() +
  xlab('Neighbourhoods') +
  ylab('Number of Occurrences') +
  ggtitle('Neighbourhoods with Most Crimes - Top 20') +
  theme_bw() +
  theme(plot.title = element_text(size = 16),
        axis.title = element_text(size = 12, face = &quot;bold&quot;))
</pre>
<p>Gives this plot:<br>
<a rel="nofollow" href="https://i2.wp.com/datascienceplus.com/wp-content/uploads/2017/10/toronto_6.png?ssl=1" target="_blank"><img sizes="(max-width: 490px) 100vw, 490px" src="https://i0.wp.com/datascienceplus.com/wp-content/uploads/2017/10/toronto_6-490x227.png?w=450&ssl=1" alt="" class="wp-image-9260" data-recalc-dims="1"></a><br>
The most dangerous neighbourhood is … Waterfront. The sprawling downtown catch-all includes not only the densely packed condo but also the boozy circus that is the entertainment district. The result: a staggering number of violent crimes and arsons.</p>
<h3>Let’s find out neighbourhoods vs. top offence types</h3>
<pre>
offence_location_group &lt;- group_by(toronto, Neighbourhood, offence)
offence_type_by_location &lt;- summarise(offence_location_group, n=n())
offence_type_by_location &lt;- offence_type_by_location[order(offence_type_by_location$n, decreasing = TRUE), ]
offence_type_by_location_top20 &lt;- head(offence_type_by_location, 20)
ggplot(aes(x = Neighbourhood, y=n, fill = offence), data=offence_type_by_location_top20) +
  geom_bar(stat = 'identity', position = position_dodge(), width = 0.8) +
  xlab('Neighbourhood') +
  ylab('Number of Occurrence') +
  ggtitle('Offence Type vs. Neighbourhood Toronto 2016') + theme_bw() +
  theme(plot.title = element_text(size = 16),
        axis.title = element_text(size = 12, face = &quot;bold&quot;),
        axis.text.x = element_text(angle = 90, hjust = 1, vjust = .4))
</pre>
<p>Gives this plot:<br>
<a rel="nofollow" href="https://i1.wp.com/datascienceplus.com/wp-content/uploads/2017/10/toronto_7.png?ssl=1" target="_blank"><img sizes="(max-width: 490px) 100vw, 490px" src="https://i2.wp.com/datascienceplus.com/wp-content/uploads/2017/10/toronto_7-490x227.png?w=450&ssl=1" alt="" class="wp-image-9261" data-recalc-dims="1"></a><br>
I did not expect something like this. It is not pretty. However, it did tell us that besides assaults, Church-Yonge Corridor and Waterfront had the most break and enter(Don’t move there!). West Humber-Clairville had the most vehicle stolen crimes(Don’t park your car there!).</p>
<h3>Let’s try something different</h3>
<pre>
crime_count % group_by(occurrencemonth, MCI) %>% summarise(Total = n())
crime_count$occurrencemonth &lt;- ordered(crime_count$occurrencemonth, levels = c('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'))
ggplot(crime_count, aes(occurrencemonth, MCI, fill = Total)) +
  geom_tile(size = 1, color = &quot;white&quot;) +
  scale_fill_viridis()  +
  geom_text(aes(label=Total), color='white') +
  ggtitle(&quot;Major Crime Indicators by Month 2016&quot;) +
  xlab('Month') +
  theme(plot.title = element_text(size = 16), 
        axis.title = element_text(size = 12, face = &quot;bold&quot;))
</pre>
<p>Gives this plot:<br>
<a rel="nofollow" href="https://i0.wp.com/datascienceplus.com/wp-content/uploads/2017/10/toronto_8.png?ssl=1" target="_blank"><img sizes="(max-width: 490px) 100vw, 490px" src="https://i1.wp.com/datascienceplus.com/wp-content/uploads/2017/10/toronto_8-490x227.png?w=450&ssl=1" alt="" class="wp-image-9262" data-recalc-dims="1"></a><br>
Much better!</p>
<p>Assault is the most common crime every month of the year with no exception. It appears that there were a little bit more assault incidents in May than the other months last year.</p>
<pre>
day_count % group_by(occurrencedayofweek, MCI) %>% summarise(Total = n())
ggplot(day_count, aes(occurrencedayofweek, MCI, fill = Total)) +
  geom_tile(size = 1, color = &quot;white&quot;) +
  scale_fill_viridis()  +
  geom_text(aes(label=Total), color='white') +
  ggtitle(&quot;Major Crime Indicators by Day of Week 2016&quot;) +
  xlab('Day of Week') +
  theme(plot.title = element_text(size = 16), 
        axis.title = element_text(size = 12, face = &quot;bold&quot;))
</pre>
<p>Gives this plot:<br>
<a rel="nofollow" href="https://i2.wp.com/datascienceplus.com/wp-content/uploads/2017/10/toronto_9.png?ssl=1" target="_blank"><img sizes="(max-width: 490px) 100vw, 490px" src="https://i1.wp.com/datascienceplus.com/wp-content/uploads/2017/10/toronto_9-490x227.png?w=450&ssl=1" alt="" class="wp-image-9263" data-recalc-dims="1"></a></p>
<p>Saturdays and Sundays had more assaults than any other days, and had less theft over than any other days. Auto thieves are busy almost every day of the week equally.<br>
I was expecting to find seasonal crime patterns such as temperature changes and daylight hours might be associated with crime throughout the year, or the beginning and end of the school year, are associated with variations in crime throughout the year. But this one-year’s worth of data is not enough to address my above concerns. I hope Toronto Police service will release more data via its open data portal in the soonest future.</p>
<h3>Homicide</h3>
<pre>
homicide &lt;- read.csv('homicide.csv', stringsAsFactors = F)
homicide$Occurrence_Date &lt;- as.Date(homicide$Occurrence_Date)
year_group &lt;- group_by(homicide, Occurrence_year, Homicide_Type)
homicide_by_year &lt;- summarise(year_group, n=n())
ggplot(aes(x = Occurrence_year, y=n, fill = Homicide_Type), data=homicide_by_year) +
  geom_bar(stat = 'identity', position = position_dodge(), width = 0.8) +
  xlab('Year') +
  ylab('Number of Homicides') +
  ggtitle('Homicide 2004-2016') + theme_bw() +
  theme(plot.title = element_text(size = 16),
        axis.title = element_text(size = 12, face = &quot;bold&quot;))
</pre>
<p>Gives this plot:<br>
<a rel="nofollow" href="https://i2.wp.com/datascienceplus.com/wp-content/uploads/2017/10/toronto_10.png?ssl=1" target="_blank"><img sizes="(max-width: 490px) 100vw, 490px" src="https://i2.wp.com/datascienceplus.com/wp-content/uploads/2017/10/toronto_10-490x227.png?w=450&ssl=1" alt="" class="wp-image-9264" data-recalc-dims="1"></a></p>
<p>2005 is Toronto’s “Year of Gun”. Eleven years later in 2016, Toronto was experiencing another spike in gun-related homicide.</p>
<pre>
homicide$month &lt;- format(as.Date(homicide$Occurrence_Date) , &quot;%B&quot;)
homicide_count % group_by(Occurrence_year, month) %>% summarise(Total = n())
homicide_count$month &lt;- ordered(homicide_count$month, levels = c('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'))
ggplot(homicide_count, aes(Occurrence_year, month, fill = Total)) +
  geom_tile(size = 1, color = &quot;white&quot;) +
  scale_fill_viridis()  +
  geom_text(aes(label=Total), color='white') +
  ggtitle(&quot;Homicides in Toronto (2004-2016)&quot;) +
  xlab('Year') +
  theme(plot.title = element_text(size = 16), 
        axis.title = element_text(size = 12, face = &quot;bold&quot;))
</pre>
<p>Gives this plot:<br>
<a rel="nofollow" href="https://i2.wp.com/datascienceplus.com/wp-content/uploads/2017/10/toronto_11.png?ssl=1" target="_blank"><img sizes="(max-width: 490px) 100vw, 490px" src="https://i0.wp.com/datascienceplus.com/wp-content/uploads/2017/10/toronto_11-490x227.png?w=450&ssl=1" alt="" class="wp-image-9265" data-recalc-dims="1"></a></p>
<p>It is worrisome to see that there is a significant increase in the total number of homicides in Toronto in 2016 compared to 2015. I hope we will have a better 2017. However, when I read that Toronto ranked safest city in North America by the Economist, I felt much safer.</p>
<h2>K-Means Clustering</h2>
<p>K-Means is one of the most popular “clustering” algorithms. It is the process of partitioning a group of data points into a small number of clusters. As in our crime data, we measure the number of assaults and other indicators, and neighbourhoods with high number of assaults will be grouped together. The goal of K-Means clustering is to assign a cluster to each data point (neighbourhood). Thus we first partition datapoints (neighbourhoods) into k clusters in which each neighbourhood belongs to the cluster with the nearest mean, serving as a prototype of the cluster.<br>
As one of the unsupervised learning algorithms,we use K-Mean to build models that help us understand our data better. It enables us to learn groupings of unlabeled data points.</p>
<h3>To do clustering analysis, our data has to look like this:</h3>
<pre>
by_groups &lt;- group_by(toronto, MCI, Neighbourhood)
groups &lt;- summarise(by_groups, n=n())
groups &lt;- groups[c(&quot;Neighbourhood&quot;, &quot;MCI&quot;, &quot;n&quot;)]
groups_wide &lt;- spread(groups, key = MCI, value = n)
</pre>
<p>Gives this table:<br>
<a rel="nofollow" href="https://i0.wp.com/datascienceplus.com/wp-content/uploads/2017/10/2017-10-28-8.png?ssl=1" target="_blank"><img sizes="(max-width: 490px) 100vw, 490px" src="https://i2.wp.com/datascienceplus.com/wp-content/uploads/2017/10/2017-10-28-8-490x227.png?w=450&ssl=1" alt="" class="wp-image-9266" data-recalc-dims="1"></a></p>
<h3>The fist column — qualitative data should be removed from the analysis</h3>
<pre>
z &lt;- groups_wide[, -c(1,1)]
</pre>
<h3>The data cannot have any missing values</h3>
<pre>
z &lt;- z[complete.cases(z), ]
</pre>
<h3>The data must be scaled for comparison</h3>
<pre>
m &lt;- apply(z, 2, mean)
s &lt;- apply(z, 2, sd)
z &lt;- scale(z, m, s)
</pre>
<h3>Determine the number of clusters</h3>
<pre>
wss &lt;- (nrow(z)-1) * sum(apply(z, 2, var))
for (i in 2:20) wss[i] &lt;- sum(kmeans(z, centers=i)$withiness)
plot(1:20, wss, type='b', xlab='Number of Clusters', ylab='Within groups sum of squares')
</pre>
<p>Gives this plot:<br>
<a rel="nofollow" href="https://i2.wp.com/datascienceplus.com/wp-content/uploads/2017/10/toronto_12.png?ssl=1" target="_blank"><img sizes="(max-width: 490px) 100vw, 490px" src="https://i1.wp.com/datascienceplus.com/wp-content/uploads/2017/10/toronto_12-490x227.png?w=450&ssl=1" alt="" class="wp-image-9267" data-recalc-dims="1"></a><br>
This plot shows a very strong elbow, based on the plot, we can say with confidence that we do not need more than two clusters (centroids).</p>
<h3>Fitting a model</h3>
<pre>
kc &lt;- kmeans(z, 2)
kc
<em>K-means clustering with 2 clusters of sizes 121, 10
Cluster means:
Assault Auto Theft Break and Enter Robbery Theft Over
1 -0.193042 -0.135490 -0.2176646 -0.1778607 -0.2288382
2 2.335808 1.639429 2.6337422 2.1521148 2.7689425
Clustering vector:
[1] 1 1 1 2 1 1 2 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 2 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
[40] 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 1 1 1 1 1 1
[79] 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 1 1 1 1 1 1 1 1 1 1 1 2 1 2 1
[118] 1 1 1 1 1 1 1 1 1 1 1 1 2 1
Within cluster sum of squares by cluster:
[1] 183.3436 170.2395
(between_SS / total_SS = 45.6 %)
Available components:
[1] &quot;cluster&quot; &quot;centers&quot; &quot;totss&quot; &quot;withinss&quot; &quot;tot.withinss&quot;
[6] &quot;betweenss&quot; &quot;size&quot; &quot;iter&quot; &quot;ifault&quot;
</em>
</pre>
<p>Interpretation:</p>
<p>* First cluster has 121 neighbourhoods, and second cluster has 10 neighbourhoods.<br>
* Cluster means: If the ranges of these numbers seem strange, it’s because we standardized the data before performing the cluster analysis. The negative values mean “lower than most” and positive values mean “higher than most”. Thus, cluster 1 are neighbourhoods with low assault, low auto theft, low break and enter, low robbery and low theft over. Cluster 2 are neighbourhoods with high assault, high auto theft, high break and enter, high robbery and high theft over. It is good that these two groups have a significant variance in every variable. It indicates that each variable plays a significant role in categorizing clusters.<br>
* Clustering vector: The first, second and third neighbourhoods should all belong to cluster 1, the fourth neighbourhood should belong to cluster 2, and so on.<br>
* A measurement that is more relative would be the withinss and betweenss.<br>
withinss tells us the sum of the square of the distance from each data point to the cluster center. Lower is better. Betweenss tells us the sum of the squared distance between cluster centers. Ideally we want cluster centers far apart from each other.<br>
* Available components is self-explanatory.</p>
<h3>Plotting the k-Means results</h3>
<pre>
z1 &lt;- data.frame(z, kc$cluster)
clusplot(z1, kc$cluster, color=TRUE, shade=F, labels=0, lines=0, main='k-Means Cluster Analysis')
</pre>
<p>Gives this plot:<br>
<a rel="nofollow" href="https://i2.wp.com/datascienceplus.com/wp-content/uploads/2017/10/toronto_13.png?ssl=1" target="_blank"><img sizes="(max-width: 490px) 100vw, 490px" src="https://i0.wp.com/datascienceplus.com/wp-content/uploads/2017/10/toronto_13-490x227.png?w=450&ssl=1" alt="" class="wp-image-9268" data-recalc-dims="1"></a></p>
<p>It appears that our choice of number of clusters is good, and we have little noise.</p>
<h2>Hierarchical Clustering</h2>
<p>For the hierarchical clustering methods, the dendrogram is the main graphical tool for getting insight into a cluster solution.</p>
<pre>
z2 &lt;- data.frame(z)
distance &lt;- dist(z2)
hc &lt;- hclust(distance)
</pre>
<p>Now that we’ve got a cluster solution. Let’s examine the results.</p>
<pre>
plot(hc, labels = groups_wide$Neighbourhood, main='Cluster Dendrogram', cex=0.65)
</pre>
<p>Gives this plot:<br>
<a rel="nofollow" href="https://i0.wp.com/datascienceplus.com/wp-content/uploads/2017/10/toronto_19.png?ssl=1" target="_blank"><img sizes="(max-width: 490px) 100vw, 490px" src="https://i2.wp.com/datascienceplus.com/wp-content/uploads/2017/10/toronto_19-490x227.png?w=450&ssl=1" alt="" class="wp-image-9269" data-recalc-dims="1"></a><br>
If we choose any height along the y-axis of the dendrogram, and move across the dendrogram counting the number of lines that we cross, each line represents a cluster. For example, if we look at a height of 10, and move across the x-axis at that height, we’ll cross two lines. That defines a two-cluster solution; by following the line down through all its branches, we can see the names of the neighbourhoods that are included in these two clusters. Looking at the dendrogram for the Toronto’s crimes data, we can see our datapoins are very imbalanced. From the top of the tree, there are two distinct groups; one group consists of brunches with brunches and more brunches, while another group only consists few neighbourhoods, and we can see these neighbourhoods are Toronto’s most dangerous neighbourhoods. However, I want to try many different groupings at once to start investigating.</p>
<pre>
counts = sapply(2:6,function(ncl)table(cutree(hc,ncl)))
names(counts) = 2:6
counts
<em>> counts
$`2`
1 2 128 3 $`3`
1 2 3 128 2 1 $`4`
1 2 3 4 121 7 2 1 $`5`
1 2 3 4 5 121 5 2 2 1 $`6`
1 2 3 4 5 6 112 5 2 9 2 1
</em>
</pre>
<p>Interpretation:<br>
* With 2-cluster solution, we have 128 neighbourhoods in cluster 1, 3 neighbourhoods in cluster 2.<br>
* With 3-cluster solution, we have 128 neighbourhoods in cluster 1, 2 neighbourhoods in cluster 2, and 1 neighbourhood in cluster 3. And so on until 6-cluster solution.</p>
<p>In practice, we’d like a solution where there aren’t too many clusters with just few observations, because it may make it difficult to interpret our results. For this exercise, I want to stick with 3-cluster solution, see what results I will obtain.</p>
<pre>
member &lt;- cutree(hc, 3)
aggregate(z, list(member), mean)
<em>aggregate(z, list(member), mean)
Group.1 Assault Auto Theft Break and Enter Robbery Theft Over
1 1 -0.09969023 -0.08067526 -0.09425688 -0.09349632 -0.1042508
2 2 5.57040267 0.57693723 4.67333848 4.14398508 5.0024522
3 3 1.61954364 9.17255898 2.71820403 3.67955938 3.3392003
</em>
</pre>
<p>In cluster 1, all the crime indicators are on the negative side, cluster 1 has a significant distinction on each variable compare with cluster 2 and cluster 3. Cluster 2 is higher in most of the crime indicators than cluster 3 except Auto Theft.</p>
<pre>
plot(silhouette(cutree(hc, 3), distance))
</pre>
<p>Gives this plot:<br>
<a rel="nofollow" href="https://i1.wp.com/datascienceplus.com/wp-content/uploads/2017/10/toronto_16.png?ssl=1" target="_blank"><img sizes="(max-width: 490px) 100vw, 490px" src="https://i1.wp.com/datascienceplus.com/wp-content/uploads/2017/10/toronto_16-490x227.png?w=450&ssl=1" alt="" class="wp-image-9270" data-recalc-dims="1"></a><br>
The silhouette width value for cluster 3 is zero. The silhouette plot indicates that we really do not need the third cluster, The vast majority of neighbourhoods belong to the first cluster, and 2-cluster will be our solution.</p>
<h2>Making a Map of Toronto’s Crimes</h2>
<p>There are many packages for plotting and manipulating spatial data in R. I am going to use ggmap to produce a simple and easy map of Toronto’ crimes.</p>
<pre>
lat &lt;- toronto$Lat
lon &lt;- toronto$Long
crimes &lt;- toronto$MCI
to_map &lt;- data.frame(crimes, lat, lon)
colnames(to_map) &lt;- c('crimes', 'lat', 'lon')
sbbox &lt;- make_bbox(lon = toronto$Long, lat = toronto$Lat, f = 0.01)
my_map &lt;- get_map(location = sbbox, maptype = &quot;roadmap&quot;, scale = 2, color=&quot;bw&quot;, zoom = 10)
ggmap(my_map) +
  geom_point(data=to_map, aes(x = lon, y = lat, color = &quot;#27AE60&quot;), 
             size = 0.5, alpha = 0.03) +
  xlab('Longitude') +
  ylab('Latitude') +
  ggtitle('Location of Major Crime Indicators Toronto 2016') +
  guides(color=FALSE)
</pre>
<p>Gives this map:<br>
<a rel="nofollow" href="https://i2.wp.com/datascienceplus.com/wp-content/uploads/2017/10/toronto_17.png?ssl=1" target="_blank"><img sizes="(max-width: 490px) 100vw, 490px" src="https://i2.wp.com/datascienceplus.com/wp-content/uploads/2017/10/toronto_17-490x227.png?w=450&ssl=1" alt="" class="wp-image-9271" data-recalc-dims="1"></a></p>
<p>It’s clear to see where the major crimes in the city occur. A large concentration in the Waterfront area, South of North York is more peaceful than any other areas. However, point-stacking is not helpful when comparing high-density areas, so let’s optimize this visualization.</p>
<pre>
ggmap(my_map) +
  geom_point(data=to_map, aes(x = lon, y = lat, color = &quot;#27AE60&quot;), 
             size = 0.5, alpha = 0.05) +
  xlab('Longitude') +
  ylab('Latitude') +
  ggtitle('Location of Major Crime Indicators Toronto 2016') +
  guides(color=FALSE) +
  facet_wrap(~ crimes, nrow = 2)
</pre>
<p>Gives this map:<br>
<a rel="nofollow" href="https://i0.wp.com/datascienceplus.com/wp-content/uploads/2017/10/toronto_18.png?ssl=1" target="_blank"><img sizes="(max-width: 490px) 100vw, 490px" src="https://i2.wp.com/datascienceplus.com/wp-content/uploads/2017/10/toronto_18-490x227.png?w=450&ssl=1" alt="" class="wp-image-9272" data-recalc-dims="1"></a><br>
This is certainly more interesting and prettier. Some crimes, such as Assaults, and Break and Enter occur all over the city, with concentration in the Waterfront areas. Other crimes, such as Auto Theft has a little more points in the west side than the east side. Robbery and Theft Over primarily have clusters in the Waterfront areas.</p>
<h2>Summary</h2>
<p>Not many more questions can be answered by looking at the data of Toronto Major crimes Indicators. But that’s okay. There’s certainly other interesting things to do with this data, such as creating a dashboard at MicroStrategy.<br>
<a rel="nofollow" href="https://i1.wp.com/datascienceplus.com/wp-content/uploads/2017/10/2017-10-30.png?ssl=1" target="_blank"><img sizes="(max-width: 490px) 100vw, 490px" src="https://i0.wp.com/datascienceplus.com/wp-content/uploads/2017/10/2017-10-30-490x256.png?w=450&ssl=1" alt="" class="wp-image-9273" data-recalc-dims="1"></a></p>
<p>As always, all the code can be found on <a rel="nofollow" href="https://github.com/susanli2016/Data-Analysis-with-R/blob/master/toronto_major_crime_indicators.Rmd" target="_blank">Github</a>. I would be pleased to receive feedback or questions on any of the above.</p>
<ul></ul>
<p><strong>
<p>Related Post</p>
<p></p></strong>
<ol>
<li><a rel="nofollow" href="https://datascienceplus.com/spring-budget-2017-circle-visualisation/" title="Permanent Link toSpring Budget 2017: Circle Visualisation" target="_blank">Spring Budget 2017: Circle Visualisation</a></li>
<li><a rel="nofollow" href="https://datascienceplus.com/qualitative-research-in-r/" title="Permanent Link toQualitative Research in R" target="_blank">Qualitative Research in R</a></li>
<li><a rel="nofollow" href="https://datascienceplus.com/multi-dimensional-reduction-and-visualisation-with-t-sne/" title="Permanent Link toMulti-Dimensional Reduction and Visualisation with t-SNE" target="_blank">Multi-Dimensional Reduction and Visualisation with t-SNE</a></li>
<li><a rel="nofollow" href="https://datascienceplus.com/comparing-trump-and-clintons-facebook-pages-during-the-us-presidential-election-2016/" title="Permanent Link toComparing Trump and Clinton’s Facebook pages during the US presidential election, 2016" target="_blank">Comparing Trump and Clinton’s Facebook pages during the US presidential election, 2016</a></li>
<li><a rel="nofollow" href="https://datascienceplus.com/analyzing-obesity-across-usa/" title="Permanent Link toAnalyzing Obesity across USA" target="_blank">Analyzing Obesity across USA</a></li>
</ol>
	<p>
<div>
<div>To <strong>leave a comment</strong> for the author, please follow the link and comment on their blog: <strong><a href="https://datascienceplus.com/exploring-clustering-and-mapping-torontos-crimes/"> R Programming – DataScience+</a></strong>.</div>
<hr>
<a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers.com</a> offers <strong><a rel="nofollow" href="https://feedburner.google.com/fb/a/mailverify?uri=RBloggers">daily e-mail updates</a></strong> about <a rel="nofollow" href="https://www.r-project.org/" title="The R Project for Statistical Computing">R</a> news and <a rel="nofollow" href="https://www.r-bloggers.com/search/tutorial" title="R tutorials">tutorials</a> on topics such as: <a rel="nofollow" href="https://www.r-bloggers.com/search/data%20science" title="Data science">Data science</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/Big%20Data" title="Big Data">Big Data, <a rel="nofollow" href="https://www.r-users.com/" title="R jobs">R jobs</a>, visualization (<a rel="nofollow" href="https://www.r-bloggers.com/search/ggplot2" title="ggplot and ggplot2 tutorials">ggplot2</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/boxplot" title="Boxplots using lattice and ggplot2 tutorials">Boxplots</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/map" title="Maps and gis">maps</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/animation" title="Animation in R">animation</a>), programming (<a rel="nofollow" href="https://www.r-bloggers.com/search/RStudio" title="RStudio IDE for R">RStudio</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/sweave" title="Sweave and literate programming">Sweave</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/LaTeX" title="LaTeX in R">LaTeX</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/SQL" title="SQL and databases">SQL</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/eclipse" title="Eclipse IDE for R">Eclipse</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/git" title="git and github, Version Control System">git</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/hadoop" title="Large data in R using Hadoop">hadoop</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/Web+Scraping" title="Web Scraping of google, facebook, yahoo, twitter and more using R">Web Scraping</a>) statistics (<a rel="nofollow" href="https://www.r-bloggers.com/search/regression" title="Regressions and ANOVA analysis tutorials">regression</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/PCA" title="principal component analysis tutorial">PCA</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/time+series" title="Time series">time series</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/trading" title="finance trading">trading</a>) and more...
<img width="1" alt="" src="http://feeds.feedburner.com/~r/RBloggers/~4/66841vwzBGE" height="1"></a></div>