Skip to content

Instantly share code, notes, and snippets.

@coppeliaMLA
Last active August 29, 2015 13:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save coppeliaMLA/9189879 to your computer and use it in GitHub Desktop.
Save coppeliaMLA/9189879 to your computer and use it in GitHub Desktop.
I've been using a lot of javascript charting and visualisation libraries recently (e.g. D3, highcharts) and found that it is quite painful to get my data into the JSON structure required by each library. Since I'm doing most of the data manipulation in R anyway it makes sense to arrange the data as a nested list in R and then transform it to JSO…
#Load libraries
library(rjson)
library(stringr)
dfToJSON<-function(df, mode='vector'){
colToList<-function(x, y){
col.json<-list()
#Build up a list of coordinates
for (i in 1:length(x)){
ni<-list(x=x[i], y=y[i])
col.json[[length(col.json)+1]]<-ni
}
return(col.json)
}
if (mode=='vector'){
for.json<-list()
for (j in 1:ncol(df)){
for.json[[length(for.json)+1]]<-list(name=colnames(df)[j] , data=df[,j])
}
}
if (mode=='coords') {
for.json<-list()
for (j in 2:ncol(df)){
for.json[[length(for.json)+1]]<-list(name=colnames(df)[j] , data=colToList(x=df[,1], y=df[,j]))
}
}
if (mode=='rowToObject') {
for.json<-list()
for (j in 1:nrow(df)){
for.json[[length(for.json)+1]]<-df[j,]
}
jj<-toJSON(for.json)
return(jj)
}
#example
test.set<-data.frame(x=1:20, y=rnorm(20), z=rnorm(20))
test.set.JSON.ts<-dfToJSON(test.set, 'coords')
test.set.JSON.vec<-dfToJSON(test.set, 'vector')
fileConn<-file("output.txt")
writeLines(test.set.JSON.vec, fileConn)
close(fileConn)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment