I have a function that lists all state postal codes and populations of each postal code when a state abbreviation is entered (for example, "KY" or "AL").
I want to return all zip codes and population groups when "ALL" is entered, but I cannot figure out how to do this. I tried writing in a for loop in a function to achieve this without success.
Here is the function:
StatePop1 <- function(StAbb="KY"){
library(rjson)
St <- c('AL','AK','AZ','AR','CA','CO','CT','DE','FL','GA','HI','ID','IL','IN','IA','KS','KY','LA','ME','MD','MA','MI','MN','MS','MO','MT','NE','NV','NH','NJ','NM','NY','NC','ND','OH','OK','OR','PA','RI','SC','SD','TN','TX','UT','VT','VA','WA','WV','WI','WY')
FI <- c('01','02','04','05','06','08','09','10','12','13','15','16','17','18','19','20','21','22','23','24','25','26','27','28','29','30','31','32','33','34','35','36','37','38','39','40','41','42','44','45','46','47','48','49','50','51','53','54','55','56')
FIPS.table <- data.frame(St,FI,stringsAsFactors = FALSE)
StAbb <- toupper(StAbb)
fips_code <- FIPS.table[FIPS.table$St == StAbb,"FI"]
json_file <- paste("http://api.census.gov/data/2010/sf1?get=P0010001&for=zip+code+tabulation+area:*&in=state:",fips_code,sep="")
json_data <- fromJSON(file=json_file)
Pop <- as.data.frame(do.call("rbind", json_data), stringsAsFactors = FALSE)
names(Pop) <- c("Population","FIPS","ZipCode")
Pop <- Pop[-1,]
Pop$Population <- as.numeric(Pop$Population)
Pop$ZipCode <- as.character(Pop$ZipCode)
Pop$State <- StAbb
Pop <- Pop[,c("State","ZipCode","Population")]
return(Pop)
}
Any help would be appreciated.