Created
November 12, 2010 16:28
-
-
Save johnjosephhorton/674300 to your computer and use it in GitHub Desktop.
R function for turning a data frame into JSON suitable for use in Protovis
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
entity.write <- function(x){ | |
out = as.character(x) | |
out = paste("\"", x, "\"", sep="") | |
out | |
} | |
toJSONdf <- function(x){ | |
str = "[" | |
for(row in 1:(dim(x)[1])){ | |
first_entry = TRUE | |
i = 0 | |
for (n in names(x)){ | |
i = i + 1 | |
if (first_entry) { | |
str = paste(str, "{", sep="") | |
first_entry = FALSE | |
} | |
str = paste(str,deparse(n),":", entity.write(x[row, n]),sep="") | |
if(i < dim(x)[2]){ | |
str = paste(str, ",", sep="") | |
} | |
} | |
str = paste(str, "}", sep="") | |
if (row < dim(x)[1]){ | |
str = paste(str, ",", sep="") | |
} | |
} | |
str = paste(str, "]", sep="") | |
str | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The rjson package is great, but it turns data frames into [x:{1,2,3}, y:{1,2,3}] where for Protovis, you want [{x:1, y:1}, {x:2,y:2}, {x:3,y:3}]. Hoping there is a smarter way to do this (and that someone else wants to add all the error checking and message).