Step 2: Show the income & population per state

# 1) Create a simpler dataframe with just the average median income and the population for each state
# use tapply to calculate average median income for each state
# and store the results in a new dataframe called "medianIncome"
income <- tapply(dfNew$Median, dfNew$state, mean )
state <- rownames(income)
medianIncome <- data.frame(state, income)
#calculate total popuation in each state
pop <- tapply(dfNew$Population, dfNew$state, sum )
state <- rownames(pop)
statePop <- data.frame(state, pop)
# merge "medianIncome" and "statePop" by common column "states"
dfSimple <- merge(medianIncome, statePop, by="state")
# 2) Add the state abbreviations and the state names as new columns
#get the state name (not just the abbreviations)
dfSimple$stateName <- state.name[match(dfSimple$state,state.abb)]
# convert "stateName" to lower case
dfSimple$stateName <- tolower(dfSimple$stateName)
# 3) Show the U.S. map, representing the color with the average median income of that state
# install.packages("ggplot2")
library(ggplot2)

## Please cite ggmap if you use it! See citation("ggmap") for details.

# get the data on the "state" to be mapped
us <- map_data("state")
# use "dfSimple" to create map and set "stateName" as map ID
mapIncome <- ggplot(dfSimple, aes(map_id = stateName))
# represent the color with average median income of each states
mapIncome <- mapIncome + geom_map(map = us, aes(fill = dfSimple$income))
# change the limits of x and y axes to print the whole map
mapIncome <- mapIncome + expand_limits(x = us$long, y = us$lat)
# make sure the map is not stretched
mapIncome <- mapIncome + coord_map()
# add a tile for the map
mapIncome <- mapIncome + ggtitle("average median Income of the U.S")
# plot the income map
mapIncome

# 4) Show the U.S. map, with color representing the population of the state
# use "dfSimple" to create map and set "stateName" as map ID
mapPop <- ggplot(dfSimple, aes(map_id = stateName))
# represent the color with population of each states
mapPop <- mapPop + geom_map(map=us, aes(fill = dfSimple$pop))
# change the limits of x and y axes to print the whole map
mapPop <- mapPop + expand_limits(x = us$long, y = us$lat)
# make sure the map is not stretched and add a title for the map
mapPop <- mapPop + coord_map() + ggtitle("Population of the U.S")
# plot the map
mapPop