Skip to content

Instantly share code, notes, and snippets.

@Protonk
Last active December 17, 2015 07:49
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Protonk/5576118 to your computer and use it in GitHub Desktop.
Save Protonk/5576118 to your computer and use it in GitHub Desktop.
# 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