You can get close by first turning the data frame into a list of lists. For example:
> a=list(unit="A",type="X",latitude=c(1,2,3),longitude=c(4,5,6))
> b=list(unit="B",type="Y",latitude=c(11,22,33),longitude=c(43,54,65))
> dlist = list(a,b)
> cat(toJSON(dlist))
[
{
"unit": "A",
"type": "X",
"latitude": [ 1, 2, 3 ],
"longitude": [ 4, 5, 6 ]
},
{
"unit": "B",
"type": "Y",
"latitude": [ 11, 22, 33 ],
"longitude": [ 43, 54, 65 ]
}
]
The problem is really how to manipulate a dataframe into the right format.
However your JSON output has mixed types -character and numeric - in vectors: ["2013-01-12 12:08:07",-21.23]
and I don't see how to get that out of R which insists on vectors being a single type. Would ["2013-01-12 12:08:07","-21.23"]
be acceptable? If so then read on...
The plyr
package has lots of code for splitting and manipulating data frames and lists. For example:
dlply(dat,~unit)
will split the dataframe by the unit
variable. You can apply a function to each of these sections and return a list. This function:
make1 <- function(d){
list(
unit=d$unit[1],
type=d$type[1],
latitude=cbind(as.character(d$date),d$latitude),
longitude=cbind(as.character(d$date),d$longitude))
}
Should convert one section into the right list format. So tell dlply
to do that to every section, and return a list of lists. That list has names, which makes toJSON
output as a named array - we need to remove the names to get a JS list.
> L = dlply(dat,~unit,make1)
> names(L)=NULL
> cat(toJSON(L))
[
{
"unit": "A",
"type": "X",
"latitude": [ [ "2013-01-12 04:08:07", "-21.21" ],
[ "2013-01-12 04:11:09", "-21.22" ],
[ "2013-01-12 04:14:08", "-21.23" ],
[ "2013-01-12 04:17:10", "-21.24" ] ],
"longitude": [ [ "2013-01-12 04:08:07", "116.78" ],
[ "2013-01-12 04:11:09", "116.77" ],
[ "2013-01-12 04:14:08", "116.76" ],
[ "2013-01-12 04:17:10", "116.75" ] ]
},
{
"unit": "B",
"type": "Y",
"latitude": [ [ "2013-01-12 04:08:07", "-21.23" ],
[ "2013-01-12 04:12:22", "-21.23" ],
[ "2013-01-12 04:12:22", "-21.23" ],
[ "2013-01-12 04:15:23", "-21.23" ] ],
"longitude": [ [ "2013-01-12 04:08:07", "116.74" ],
[ "2013-01-12 04:12:22", "116.75" ],
[ "2013-01-12 04:12:22", "116.75" ],
[ "2013-01-12 04:15:23", "116.76" ] ]
}
]
Fun eh?