-
-
Save rwaldron/5775783 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
# fast json library for R. | |
# drop in replacement for rjson (another library) | |
# use whatever you prefer | |
library(RJSONIO) | |
## hardcoded for this test | |
ny.json <- fromJSON("/Users/protonk/dev/R/nomnom/data.json") | |
unflatten <- function(json) { | |
# build vectors of possible names | |
# bit magical, but we strip list names, then | |
# convert to a flat character vector and extract those | |
legis.names <- unique(names(unlist(unname(json)))) | |
# prefilling the vector outside the loop is a nice | |
# performance gain | |
prefill <- vector("numeric", length = length(legis.names)) | |
sortStretch <- function(orig) { | |
# Assign all to NA, so that... | |
prefill[] <- NA | |
# we replace ONLY those elements whose names occur in | |
# this list element's vector with the content of | |
# this element's vector | |
prefill[match(names(orig), legis.names)] <- orig | |
return(prefill) | |
} | |
square <- lapply(json, sortStretch) | |
# pack into a matrix, now that they are the same length | |
# then transpose because that's what rollcall() expects | |
out.mat <- t(do.call(rbind, square)) | |
# name (we've already assured that the sorting order will be correct) | |
rownames(out.mat) <- legis.names | |
return(out.mat) | |
} | |
ny.mat <- unflatten(ny.json) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment