I want to turn an R data.frame into a JSON object in order to use it for preparing data visualizations with d3.js. I found a lot of questions that asked how to get JSON into
I am pigging backing off of user1609452's answer and answering the question about non regular file hierarchies. If you have a column where some data have children and some do not, use the following:
makeList<-function(x){
if(ncol(x)>2){
listSplit<-split(x[-1],x[1],drop=T)
lapply(names(listSplit),function(y){
if(as.character(listSplit[[y]][1,1]) > 0){
list(name=y,children=makeList(listSplit[[y]]))
} else {
list(name=y,size=listSplit[[y]][1,2])
}
})
}else{
lapply(seq(nrow(x[1])),function(y){list(name=x[,1][y],size=x[,2][y])})
}
}
Basically we check if the current row has more children or if it simply needs to have size appended to it.