http://reed.edu/data-at-reed/resources/R/loops_with_ggplot2.html
library(stringr)
library(reshape2)
library(ggplot2)
library(ggthemes)
library(pander)
results <- "/Users/majerus/Desktop/NJAIS/results/"
labor <- "/Users/majerus/Desktop/NJAIS/data/dept_labor/age_lvl/"
file_list <- list.files(path=labor, pattern="*.csv")
data.labor <-
do.call("rbind",
lapply(file_list,
function(x)
cbind(year = as.numeric(str_sub(x, 1, 4)),
read.csv(paste(labor, x, sep=''),
stringsAsFactors = FALSE))))
data.labor[,c(3:12)] <- lapply(
data.labor[,c(3:12)],
function(x) {as.numeric(
gsub(",", "", x))})
data.labor <- subset(data.labor, data.labor$year!=2010)
colnames(data.labor) <- c("Year", "County", "Total",
"Under 5", '5 to 9 years', '10 to 14 years', '15 to 19 years',
"X20.24", "X25.29", "X30.34", "X35.39", "X40.44")
keep <- c("Year", "County", "Total", 'Under 5',
'5 to 9 years', '10 to 14 years', '15 to 19 years')
data.labor <- data.labor[keep]
data.labor.long <- melt(data.labor, id.vars=c("County", "Year"), variable.name="category")
data.labor.long <- subset(data.labor.long, data.labor.long$category!='Total')
data.labor.long <- subset(data.labor.long, data.labor.long$County!='New Jersey')
county.graph <- function(df, na.rm = TRUE, ...){
county_list <- unique(df$County)
for (i in seq_along(county_list)) {
plot <-
ggplot(subset(df, df$County==county_list[i]),
aes(Year, value/1000, group = County, colour = category)) +
geom_line(size=2) +
facet_wrap( ~ category, ncol=2) +
theme_pander() +
theme(legend.position="none") +
scale_y_continuous("County Population within Age Categories (thousands)",
limits=c(0, max(df$value[df$County==county_list[i]]))/1000) +
scale_x_continuous("Year") +
ggtitle(paste(county_list[i], ' County, New Jersey \n',
"County Population Projection within Age Categories (thousands) \n",
sep=''))
print(plot)
}
}
county.graph(data.labor.long)