Created
October 20, 2013 03:57
-
-
Save timmyshen/7064888 to your computer and use it in GitHub Desktop.
Write a function named count that takes one argument, a character string indicating the
cause of death. The function should then return an integer representing the number of
homicides from that cause in the dataset. If no cause of death is specied, then the function
should return an error message via the stop function.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# count.R | |
# setwd("~/ComputingForDataAnalysis/Assignment4") | |
count <- function(cause = NULL) { | |
## Check that "cause" is non-NULL; else throw error | |
if (is.null(cause)) { | |
stop("Cause has not been specified.") | |
} | |
## Check that specific "cause" is allowed; else throw error | |
allowed_causes = c("asphyxiation", "blunt force", "other", "shooting", "stabbing", "unknown") | |
if (!cause %in% allowed_causes) { | |
stop("The cause specified is not allowed.") | |
} | |
## Read "homicides.txt" data file | |
homicides <- readLines("homicides.txt") | |
## Extract causes of death | |
cause_regex_pattern <- "[Cc]ause" | |
# 212, 213, 236, 238, 515 records do not have cause of death. | |
# To see this, use the following statement | |
# grep(pattern=cause_regex_pattern, x=homicides) | |
matched_positions <- regexpr(pattern=cause_regex_pattern, text=homicides) | |
my_count = 0 | |
if (cause == "asphyxiation") { | |
my_count = length(grep("Cause: [Aa]sphyxiation", homicides)) | |
} | |
else if (cause == "blunt force") { | |
my_count = length(grep("Cause: [Bb]lunt [Ff]orce", homicides)) | |
} | |
else if (cause == "other") { | |
my_count = length(grep("Cause: [Oo]ther", homicides)) | |
} | |
else if (cause == "shooting") { | |
my_count = length(grep("Cause: [Ss]hooting", homicides)) | |
} | |
else if (cause == "stabbing") { | |
my_count = length(grep("Cause: [Ss]tabbing", homicides)) | |
} | |
else if (cause == "unknown") { | |
my_count = length(grep("Cause: [Uu]nknown", homicides)) | |
} | |
else {stop("Impossible error.")} | |
## Return integer containing count of homicides for that cause | |
return(my_count) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment