How many rows of data (observations) are in this dataset?
data=read.csv("mvtWeek1.csv")
nrow(data)
[1] 191641
How many variables are in this dataset?
ncol(data)
[1] 11
Using the “max” function, what is the maximum value of the variable “ID”?
max(data$ID)
[1] 9181151
What is the minimum value of the variable “Beat”?
min(data$Beat)
[1] 111
How many observations have value TRUE in the Arrest variable (this is the number of crimes for which an arrest was made)?
arrest=subset(data,Arrest=="TRUE")
nrow(arrest)
[1] 15536
How many observations have a LocationDescription value of ALLEY?
locateiondscp=subset(data,LocationDescription=="ALLEY")
nrow(locateiondscp)
[1] 2308
In many datasets, like this one, you have a date field. Unfortunately, R does not automatically recognize entries that look like dates. We need to use a function in R to extract the date and time. Take a look at the first entry of Date (remember to use square brackets when looking at a certain entry of a variable).
In what format are the entries in the variable Date?
print("use data$Date function to know the format")
[1] "use data$Date function to know the format"
print("Month/Day/Year Hour:Minute")
[1] "Month/Day/Year Hour:Minute"
Now, let’s convert these characters into a Date object in R. In your R console, type
DateConvert = as.Date(strptime(mvt$Date, "%m/%d/%y %H:%M"))
This converts the variable “Date” into a Date object in R. Take a look at the variable DateConvert using the summary function.
What is the month and year of the median date in our dataset? Enter your answer as “Month Year”, without the quotes. (Ex: if the answer was 2008-03-28, you would give the answer “March 2008”, without the quotes.)
Sys.setlocale("LC_TIME", "English")
[1] "English_United States.1252"
DateConvert = as.Date(strptime(data$Date, "%m/%d/%y %H:%M"))
Med=median(DateConvert)
MedMandY=format(Med,format="%B %Y")
print(MedMandY)
[1] "May 2006"
Now, let’s extract the month and the day of the week, and add these variables to our data frame mvt. We can do this with two simple functions. Type the following commands in R:
mvt$Month = months(DateConvert)
mvt$Weekday = weekdays(DateConvert)
This creates two new variables in our data frame, Month and Weekday, and sets them equal to the month and weekday values that we can extract from the Date object. Lastly, replace the old Date variable with DateConvert by typing:
mvt$Date = DateConvert
Using the table command, answer the following questions.
In which month did the fewest motor vehicle thefts occur?
data$Date=DateConvert
data$Month = months(DateConvert)
data$Weekday = weekdays(DateConvert)
which.min(table(data$Month))
February
4
On which weekday did the most motor vehicle thefts occur?
which.max(table(data$Weekday))
Friday
1
Each observation in the dataset represents a motor vehicle theft, and the Arrest variable indicates whether an arrest was later made for this theft. Which month has the largest number of motor vehicle thefts for which an arrest was made?
arrestmonth=subset(data,data$Arrest==T)
which.max(table(arrestmonth$Month))
January
5
Now, let’s make some plots to help us better understand how crime has changed over time in Chicago. Throughout this problem, and in general, you can save your plot to a file. For more information, this website very clearly explains the process.
First, let’s make a histogram of the variable Date. We’ll add an extra argument, to specify the number of bars we want in our histogram. In your R console, type
hist(mvt$Date, breaks=100)
hist(data$Date,breaks=100)
Looking at the histogram, answer the following questions.
In general, does it look like crime increases or decreases from 2002 - 2012?
print("Decreases")
[1] "Decreases"
In general, does it look like crime increases or decreases from 2005 - 2008?
print("Decreases")
[1] "Decreases"
Now, let’s see how arrests have changed over time. Create a boxplot of the variable “Date”, sorted by the variable “Arrest” (if you are not familiar with boxplots and would like to learn more, check out this tutorial). In a boxplot, the bold horizontal line is the median value of the data, the box shows the range of values between the first quartile and third quartile, and the whiskers (the dotted lines extending outside the box) show the minimum and maximum values, excluding any outliers (which are plotted as circles). Outliers are defined by first computing the difference between the first and third quartile values, or the height of the box. This number is called the Inter-Quartile Range (IQR). Any point that is greater than the third quartile plus the IQR or less than the first quartile minus the IQR is considered an outlier.
Does it look like there were more crimes for which arrests were made in the first half of the time period or the second half of the time period? (Note that the time period is from 2001 to 2012, so the middle of the time period is the beginning of 2007.)
boxplot(data$Date~data$Arrest)
print("First half")
[1] "First half"
Let’s investigate this further. Use the table function for the next few questions.
For what proportion of motor vehicle thefts in 2001 was an arrest made?
Note: in this question and many others in the course, we are asking for an answer as a proportion. Therefore, your answer should take a value between 0 and 1.
data$Year=format(DateConvert,"%Y")
table(data$Arrest,data$Year)
2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012
FALSE 18517 16638 14859 15169 14956 14796 13068 13425 11327 14796 15012 13542
TRUE 2152 2115 1798 1693 1528 1302 1212 1020 840 701 625 550
print(2152/(18517+2152))
[1] 0.1041173
For what proportion of motor vehicle thefts in 2007 was an arrest made?
print(1212/(1212+13068))
[1] 0.08487395
For what proportion of motor vehicle thefts in 2012 was an arrest made?
print(550/(13542+550))
[1] 0.03902924
Since there may still be open investigations for recent crimes, this could explain the trend we are seeing in the data. There could also be other factors at play, and this trend should be investigated further. However, since we don’t know when the arrests were actually made, our detective work in this area has reached a dead end.
Analyzing this data could be useful to the Chicago Police Department when deciding where to allocate resources. If they want to increase the number of arrests that are made for motor vehicle thefts, where should they focus their efforts?
We want to find the top five locations where motor vehicle thefts occur. If you create a table of the LocationDescription variable, it is unfortunately very hard to read since there are 78 different locations in the data set. By using the sort function, we can view this same table, but sorted by the number of observations in each category. In your R console, type:
sort(table(mvt$LocationDescription))
Which locations are the top five locations for motor vehicle thefts, excluding the “Other” category? You should select 5 of the following options.
sort(table(data$LocationDescription),decreasing = TRUE)
STREET PARKING LOT/GARAGE(NON.RESID.)
156564 14852
OTHER ALLEY
4573 2308
GAS STATION DRIVEWAY - RESIDENTIAL
2111 1675
RESIDENTIAL YARD (FRONT/BACK) RESIDENCE
1536 1302
RESIDENCE-GARAGE VACANT LOT/LAND
1176 985
VEHICLE NON-COMMERCIAL SIDEWALK
817 462
CHA PARKING LOT/GROUNDS AIRPORT/AIRCRAFT
405 363
POLICE FACILITY/VEH PARKING LOT PARK PROPERTY
266 255
SCHOOL, PUBLIC, GROUNDS APARTMENT
206 184
SPORTS ARENA/STADIUM CTA GARAGE / OTHER PROPERTY
166 148
COMMERCIAL / BUSINESS OFFICE HOTEL/MOTEL
126 124
SCHOOL, PUBLIC, BUILDING HOSPITAL BUILDING/GROUNDS
114 101
GROCERY FOOD STORE CHURCH/SYNAGOGUE/PLACE OF WORSHIP
80 56
RESTAURANT GOVERNMENT BUILDING/PROPERTY
49 48
COLLEGE/UNIVERSITY GROUNDS CAR WASH
47 44
CONSTRUCTION SITE SMALL RETAIL STORE
35 33
OTHER RAILROAD PROP / TRAIN DEPOT AIRPORT EXTERIOR - NON-SECURE AREA
28 24
SCHOOL, PRIVATE, GROUNDS VEHICLE-COMMERCIAL
23 23
DEPARTMENT STORE HIGHWAY/EXPRESSWAY
22 22
NURSING HOME/RETIREMENT HOME TAXICAB
21 21
MOVIE HOUSE/THEATER RESIDENCE PORCH/HALLWAY
18 18
BAR OR TAVERN WAREHOUSE
17 17
FACTORY/MANUFACTURING BUILDING SCHOOL, PRIVATE, BUILDING
16 14
TAVERN/LIQUOR STORE AIRPORT PARKING LOT
14 11
AIRPORT VENDING ESTABLISHMENT ATHLETIC CLUB
10 9
DRUG STORE OTHER COMMERCIAL TRANSPORTATION
8 8
BANK CONVENIENCE STORE
7 7
FOREST PRESERVE AIRPORT TERMINAL UPPER LEVEL - NON-SECURE AREA
6 5
CHA APARTMENT DAY CARE CENTER
5 5
FIRE STATION ABANDONED BUILDING
5 4
AIRPORT BUILDING NON-TERMINAL - NON-SECURE AREA BARBERSHOP
4 4
LAKEFRONT/WATERFRONT/RIVERBANK LIBRARY
4 4
SAVINGS AND LOAN BOWLING ALLEY
4 3
CLEANING STORE MEDICAL/DENTAL OFFICE
3 3
BRIDGE COLLEGE/UNIVERSITY RESIDENCE HALL
2 2
CURRENCY EXCHANGE AIRPORT BUILDING NON-TERMINAL - SECURE AREA
2 1
AIRPORT EXTERIOR - SECURE AREA ANIMAL HOSPITAL
1 1
APPLIANCE STORE CTA TRAIN
1 1
JAIL / LOCK-UP FACILITY NEWSSTAND
1 1
print("Street,Parking Lot/Garage,Alley,Gas Station,Driveway")
[1] "Street,Parking Lot/Garage,Alley,Gas Station,Driveway"
Create a subset of your data, only taking observations for which the theft happened in one of these five locations, and call this new data set “Top5”. To do this, you can use the | symbol. In lecture, we used the & symbol to use two criteria to make a subset of the data. To only take observations that have a certain value in one variable or the other, the | character can be used in place of the & symbol. This is also called a logical “or” operation.
Alternately, you could create five different subsets, and then merge them together into one data frame using rbind.
How many observations are in Top5?
count2=data$LocationDescription
Top5=subset(data,count2=="STREET"|count2=="PARKING LOT/GARAGE(NON.RESID.)"|count2=="ALLEY"|count2=="GAS STATION"|count2=="DRIVEWAY - RESIDENTIAL")
nrow(Top5)
[1] 177510
R will remember the other categories of the LocationDescription variable from the original dataset, so running table(Top5$LocationDescription) will have a lot of unnecessary output. To make our tables a bit nicer to read, we can refresh this factor variable. In your R console, type:
Top5$LocationDescription = factor(Top5$LocationDescription)
If you run the str or table function on Top5 now, you should see that LocationDescription now only has 5 values, as we expect.
Use the Top5 data frame to answer the remaining questions.
One of the locations has a much higher arrest rate than the other locations. Which is it? Please enter the text in exactly the same way as how it looks in the answer options for Problem 4.1.
Top5$LocationDescription = factor(Top5$LocationDescription)
table(Top5$Arrest,Top5$LocationDescription)
ALLEY DRIVEWAY - RESIDENTIAL GAS STATION PARKING LOT/GARAGE(NON.RESID.) STREET
FALSE 2059 1543 1672 13249 144969
TRUE 249 132 439 1603 11595
alleyArrest=249/(2059+249)
drivewayArrest=132/(1543+132)
gasArrest=439/(1672+439)
parkingArrest=1603/(13249+1603)
streetArrest=11595/(144969+11595)
print('Gas Station')
[1] "Gas Station"
On which day of the week do the most motor vehicle thefts at gas stations happen? (Monday~Sunday)
gashappen=subset(Top5,Top5$LocationDescription=="GAS STATION")
sort(table(gashappen$Weekday),decreasing = TRUE)
Saturday Sunday Friday Thursday Monday Wednesday Tuesday
338 336 332 282 280 273 270
print('Saturday')
[1] "Saturday"
On which day of the week do the fewest motor vehicle thefts in residential driveways happen?(Monday~Sunday)
drivewayshappen=subset(Top5,Top5$LocationDescription=="DRIVEWAY - RESIDENTIAL")
sort(table(drivewayshappen$Weekday),decreasing = TRUE)
Thursday Friday Monday Tuesday Wednesday Sunday Saturday
263 257 255 243 234 221 202
print('Saturday')
[1] "Saturday"