Created
November 23, 2011 08:32
-
-
Save vst/1388190 to your computer and use it in GitHub Desktop.
Marshalling between xts objects and JSON representations of xts objects.
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
##' Declares the generic as.json method. | |
##' | |
##' @param x the object to be marshalled to JSON | |
##' @param ... extra arguments to the actual function | |
##' @return a JSON representation of the consumed object. | |
##' @export | |
as.json = function (x, ...) { | |
UseMethod("as.json") | |
} | |
##' Declares the as.json method for xts instances | |
##' | |
##' @param x the xts object to be marshalled to JSON | |
##' @param ... extra arguments to the data.frame | |
##' @return a JSON representation of the consumed xts object. | |
##' @export | |
as.json.xts = function (x, ...) { | |
## Prepare the data frame first: | |
retval = data.frame(cbind(Index=as.character(index(x)), coredata(x)), ...) | |
## Remove the row names: | |
rownames(retval) = NULL | |
## Done, return the JSON: | |
return(toJSON(as.list(retval))) | |
} | |
##' Consumes a JSON string and returns an xts instance. | |
##' | |
##' @param x the JSON representation of the xts instance. The first | |
##' column is meant to be the index of the xts instance to be | |
##' constructed. | |
##' @param ... extra parameters to xts function. | |
##' @return the xts instance. | |
##' @export | |
xtsFromJSON = function (x, ...) { | |
## Get the list: | |
retval = as.data.frame(fromJSON(x)) | |
## Construct and return xts instance: | |
return(xts(retval[,-1], order.by=as.POSIXct(retval[,1]), ...)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Just what i was looking for!
Now I can convert my xts object to a consumable json for javascript charting libraries.
Thanks