Skip to content

Instantly share code, notes, and snippets.

@timmyshen
Created October 20, 2013 03:59
Show Gist options
  • Save timmyshen/7064896 to your computer and use it in GitHub Desktop.
Save timmyshen/7064896 to your computer and use it in GitHub Desktop.
The goal of this part is to write a function called agecount that returns the number of homicide victims of a given age. For most (but not all) records there is an indication of the age of the victim. Your function should take one argument, the age of the victim(s), extract the age of the victim from each record and then return a count of the nu…
# agecount.R
agecount <- function(age = NULL) {
## Check that "age" is non-NULL; else throw error
if (is.null(age)) {
stop("Age input cannot be NULL")
}
## Read "homicides.txt" data file
homicides <- readLines("homicides.txt")
## Extract ages of victims; ignore records where no age is
## given
age_str = as.character(x=age)
age_pattern = paste("", age_str, "years old")
# print(age_pattern)
length(grep(pattern=age_pattern, x=homicides))
## Return integer containing count of homicides for that age
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment