Created
February 12, 2013 20:55
-
-
Save muschellij2/4773311 to your computer and use it in GitHub Desktop.
How to read data into a data.frame for Baltimore City 311 system.
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
rm(list=ls()) | |
library(XML) | |
library(RJSONIO) | |
library(stringr) | |
ff <- url("http://311.baltimorecity.gov/open311/v2/requests.json?api&jurisdiction_id=baltimorecity.gov") | |
x <- readLines(ff) | |
close(ff) | |
J <- fromJSON(x, asText=TRUE ) | |
cnames <- c("service_request_id", "token", "status","service_name", "service_code", "description", "requested_datetime", "updated_datetime", "lat", "long", "address", "status_notes") | |
J <- lapply(J, function(x) { | |
if (! "address" %in% names(x)) x <- c(x, address=NA) | |
if (! "status_notes" %in% names(x)) x <- c(x, status_notes=NA) | |
x <- x[!names(x) %in% "media_url"] | |
x <- x[cnames] | |
x | |
}) | |
data <- data.frame(do.call("rbind", J), stringsAsFactors=FALSE) | |
for (icol in cnames) { | |
x <- data[, icol] | |
if (class(x) == "list") { | |
#print(icol) | |
x <- sapply(x, function(dd) ifelse(is.null(dd), NA, dd)) | |
data[, icol] <- unlist(x) | |
} | |
data[,icol][data[,icol] == ""] <- NA | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment