For others trying to answer, the toJSONArray[2]
functions are in the rCharts
package. Your solution is pretty compact, but can be de-looped and tightened a bit with sapply
and split
:
library(rjson)
library(rCharts)
x <- 1:5
y <- c('a', 'b' ,'c' ,'d' ,'e')
z <- c(1, 1, 1, 2, 2)
df <- data.frame(x, y, z)
toJSON(df)
out <- toJSONArray(sapply(split(df[,1:2], df$z), function(x) {
toJSONArray2(x, names=FALSE, json = FALSE)
}))
# doing gsub only for SO example output
cat(gsub("\\n", "", out))
## [ [ [ 1,"a" ],[ 2,"b" ],[ 3,"c" ] ],[ [ 4,"d" ],[ 5,"e" ] ] ]
Per requester, let's take a look at the toJSONArray[2]()
function implementations in rCharts
:
toJSONArray <- function(obj, json = TRUE, nonames = TRUE){
list2keyval <- function(l){
keys = names(l)
lapply(keys, function(key){
list(key = key, values = l[[key]])
})
}
obj2list <- function(df){
l = plyr::alply(df, 1, as.list)
if(nonames){ names(l) = NULL }
return(l)
}
if (json){
toJSON(obj2list(obj))
} else {
obj2list(obj)
}
}
toJSONArray2 <- function(obj, json = TRUE, names = TRUE, ...){
value = lapply(1:nrow(obj), function(i) {
res <- as.list(obj[i, ])
if (!names) names(res) <- NULL # remove names (e.g. {x = 1, y = 2} => {1, 2})
return(res)
})
if (json){
return(toJSON(value, .withNames = F, ...))
} else {
names(value) <- NULL;
return(value)
}
}
Those functions are pretty optimized, but toJSONArray2
is basically using one of the apply
functions as a for
loop, so let's see if a self-encoding of JSON for your needs is any better. The following might be faster for you, but you'll prbly need to tweak it a bit more for your production-code (and if you need the integers de-quoted):
out <- sapply(split(df[,1:2], df$z), function(x) {
out.2 <- apply(x, 1, function(y) {
return(paste0(toJSON(unlist(as.list(y)), .withNames = FALSE), sep=",", collapse=""))
})
out.2 <- paste(out.2, sep=", ", collapse=" ")
out.2 <- gsub(",$", "", out.2)
return(sprintf("[ %s ], ", out.2))
})
cat(sprintf("[ %s ]", gsub(", $", "", paste(unlist(out), collapse=""))))
## [ [ [ "1", "a" ], [ "2", "b" ], [ "3", "c" ] ], [ [ "4", "d" ], [ "5", "e" ] ] ]
It shares some similar patterns as the rCharts
implementation but is completely focused on slapping rows of a factor-split data frame into the format you need.