Last active
August 29, 2015 14:21
-
-
Save jschaub30/8d13e24422cccee13b6d to your computer and use it in GitHub Desktop.
R recursive function to write hierarchical data frame to json file with childen
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
# http://stackoverflow.com/questions/12818864/how-to-write-to-json-with-children-from-r | |
# example input | |
# year month size | |
# 2007 1 100 | |
# ... | |
# 2007 12 850 | |
# 2008 1 432 | |
# ... | |
makeList <- function(x){ | |
if(ncol(x) > 2){ | |
listSplit <- split(x[-1], x[1], drop = T) | |
lapply( names(listSplit), | |
function(y){ | |
list(name = y, children = makeList(listSplit[[y]])) | |
} ) | |
} | |
else { | |
lapply( seq(nrow(x[1])), | |
function(y){ | |
list(name = x[,1][y], size = x[,2][y]) | |
} ) | |
} | |
} | |
jsonStr <- toJSON(list(name="user",children=makeList(d2))) | |
fileConn<-file("data.json") | |
writeLines(jsonStr, fileConn) | |
close(fileConn) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment