How many rows of data (observations) are in this dataset?
Sys.setlocale("LC_ALL","C")
[1] "C"
D = read.csv("data/mvtWeek1.csv")
nrow(D)
[1] 191641
How many variables are in this dataset?
ncol(D)
[1] 11
Using the “max” function, what is the maximum value of the variable “ID”?
which.max(D$ID)
[1] 18134
D$ID[18134]
[1] 9181151
What is the minimum value of the variable “Beat”?
which.min(D$Beat)
[1] 4756
D$Beat[4756]
[1] 111
How many observations have value TRUE in the Arrest variable (this is the number of crimes for which an arrest was made)?
K =table(D$Arrest)
K[2]
TRUE
15536
How many observations have a LocationDescription value of ALLEY?
sum(D$LocationDescription==c("ALLEY"))
[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?
D$Date[1]
[1] "2012-12-31"
# 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.)
DateConvert = as.Date(strptime(D$Date, "%m/%d/%y %H:%M"))
summary(DateConvert)
Min. 1st Qu. Median Mean 3rd Qu. Max.
"2001-01-01" "2003-07-10" "2006-05-21" "2006-08-23" "2009-10-24" "2012-12-31"
median(DateConvert)
[1] "2006-05-21"
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?
D$Month = months(DateConvert)
D$Weekday = weekdays(DateConvert)
D$Date = DateConvert
sort(table(D$Month))
February April March June May January September November December August July October
13511 15280 15758 16002 16035 16047 16060 16063 16426 16572 16801 17086
On which weekday did the most motor vehicle thefts occur?
sort(table(D$Weekday),TRUE)
Friday Wednesday Monday Thursday Saturday Tuesday Sunday
29284 27416 27397 27319 27118 26791 26316
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?
table(D$Arrest,D$Month)
一月 七月 九月 二月 八月 十一月 十二月 十月 三月
FALSE 14612 15477 14812 12273 15243 14807 15029 15744 14460
TRUE 1435 1324 1248 1238 1329 1256 1397 1342 1298
五月 六月 四月
FALSE 14848 14772 14028
TRUE 1187 1230 1252
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)
Looking at the histogram, answer the following questions.
In general, does it look like crime increases or decreases from 2002 - 2012?
# Decreases
In general, does it look like crime increases or decreases from 2005 - 2008?
# 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.)
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.
sum(D$Year==2001 & D$Arrest=="TRUE") /sum(D$Year==2001)
[1] 0.1041173
For what proportion of motor vehicle thefts in 2007 was an arrest made?
sum(D$Year==2007 & D$Arrest=="TRUE") /sum(D$Year==2007)
[1] 0.08487395
For what proportion of motor vehicle thefts in 2012 was an arrest made?
sum(D$Year==2012 & D$Arrest=="TRUE") /sum(D$Year==2012)
[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(D$LocationDescription),decreasing= TRUE)
STREET PARKING LOT/GARAGE(NON.RESID.) OTHER
156564 14852 4573
ALLEY GAS STATION DRIVEWAY - RESIDENTIAL
2308 2111 1675
RESIDENTIAL YARD (FRONT/BACK) RESIDENCE RESIDENCE-GARAGE
1536 1302 1176
VACANT LOT/LAND VEHICLE NON-COMMERCIAL SIDEWALK
985 817 462
CHA PARKING LOT/GROUNDS AIRPORT/AIRCRAFT POLICE FACILITY/VEH PARKING LOT
405 363 266
PARK PROPERTY SCHOOL, PUBLIC, GROUNDS APARTMENT
255 206 184
SPORTS ARENA/STADIUM CTA GARAGE / OTHER PROPERTY COMMERCIAL / BUSINESS OFFICE
166 148 126
HOTEL/MOTEL SCHOOL, PUBLIC, BUILDING HOSPITAL BUILDING/GROUNDS
124 114 101
GROCERY FOOD STORE CHURCH/SYNAGOGUE/PLACE OF WORSHIP RESTAURANT
80 56 49
GOVERNMENT BUILDING/PROPERTY COLLEGE/UNIVERSITY GROUNDS CAR WASH
48 47 44
CONSTRUCTION SITE SMALL RETAIL STORE OTHER RAILROAD PROP / TRAIN DEPOT
35 33 28
AIRPORT EXTERIOR - NON-SECURE AREA SCHOOL, PRIVATE, GROUNDS VEHICLE-COMMERCIAL
24 23 23
DEPARTMENT STORE HIGHWAY/EXPRESSWAY NURSING HOME/RETIREMENT HOME
22 22 21
TAXICAB MOVIE HOUSE/THEATER RESIDENCE PORCH/HALLWAY
21 18 18
BAR OR TAVERN WAREHOUSE FACTORY/MANUFACTURING BUILDING
17 17 16
SCHOOL, PRIVATE, BUILDING TAVERN/LIQUOR STORE AIRPORT PARKING LOT
14 14 11
AIRPORT VENDING ESTABLISHMENT ATHLETIC CLUB DRUG STORE
10 9 8
OTHER COMMERCIAL TRANSPORTATION BANK CONVENIENCE STORE
8 7 7
FOREST PRESERVE AIRPORT TERMINAL UPPER LEVEL - NON-SECURE AREA CHA APARTMENT
6 5 5
DAY CARE CENTER FIRE STATION ABANDONED BUILDING
5 5 4
AIRPORT BUILDING NON-TERMINAL - NON-SECURE AREA BARBERSHOP LAKEFRONT/WATERFRONT/RIVERBANK
4 4 4
LIBRARY SAVINGS AND LOAN BOWLING ALLEY
4 4 3
CLEANING STORE MEDICAL/DENTAL OFFICE BRIDGE
3 3 2
COLLEGE/UNIVERSITY RESIDENCE HALL CURRENCY EXCHANGE AIRPORT BUILDING NON-TERMINAL - SECURE AREA
2 2 1
AIRPORT EXTERIOR - SECURE AREA ANIMAL HOSPITAL APPLIANCE STORE
1 1 1
CTA TRAIN JAIL / LOCK-UP FACILITY NEWSSTAND
1 1 1
# Street,Parking Lot/Garage (Non-Residential),Alley,Gas Station,Driveway (Residential)
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?
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.
e=(table(TOP5$LocationDescription, TOP5$Arrest))
ALLEY=(e[1,2])/(e[1,1]+e[1,2])
DRIVEWAY_RESIDENTIAL=(e[2,2])/(e[2,1]+e[2,2])
GAS_STATION=(e[3,2])/(e[3,1]+e[3,2])
PARKING_LOT=(e[4,2])/(e[4,1]+e[4,2])
STREET=(e[5,2])/(e[5,1]+e[5,2])
max(c(ALLEY,DRIVEWAY_RESIDENTIAL,GAS_STATION,PARKING_LOT,STREET))
[1] 0.2079583
which.max((c(ALLEY,DRIVEWAY_RESIDENTIAL,GAS_STATION,PARKING_LOT,STREET)))
[1] 3
On which day of the week do the most motor vehicle thefts at gas stations happen? (Monday~Sunday)
sort(table(TOP5$LocationDescription,TOP5$Weekday)[3,],TRUE)
Saturday Sunday Friday Thursday Monday Wednesday Tuesday
338 336 332 282 280 273 270
#Saturday
On which day of the week do the fewest motor vehicle thefts in residential driveways happen?(Monday~Sunday)
sort(table(TOP5$LocationDescription,TOP5$Weekday)[2,],FALSE)
Saturday Sunday Wednesday Tuesday Monday Friday Thursday
202 221 234 243 255 257 263
#Saturday