Skip to content

Instantly share code, notes, and snippets.

@jfreels
Last active December 24, 2015 02:19
Show Gist options
  • Save jfreels/6729994 to your computer and use it in GitHub Desktop.
Save jfreels/6729994 to your computer and use it in GitHub Desktop.
R to JSON: long vs. wide data.frame comparison
{
"date" : [
"1997-01-31",
"1997-02-28",
"1997-03-31",
"1997-04-30",
"1997-05-31",
"1997-01-31",
"1997-02-28",
"1997-03-31",
"1997-04-30",
"1997-05-31"
],
"variable" : [
"Convertible.Arbitrage",
"Convertible.Arbitrage",
"Convertible.Arbitrage",
"Convertible.Arbitrage",
"Convertible.Arbitrage",
"CTA.Global",
"CTA.Global",
"CTA.Global",
"CTA.Global",
"CTA.Global"
],
"value" : [
0.0119,
0.0123,
0.0078,
0.0086,
0.0156,
0.0393,
0.0298,
-0.0021,
-0.017,
-0.0015
]
}
### Load and format data
require(PerformanceAnalytics)
data(edhec)
# first 2 columns and first 5 rows of edhec as a data frame
edhec_wide<-data.frame(date=index(edhec),coredata(edhec))[1:5,1:3]
edhec_wide$date<-as.character(edhec_wide$date)
# edhec_wide melted to long format
edhec_long<-melt(edhec_wide,id.vars='date')
# convert to JSON
require(RJSONIO)
cat(toJSON(edhec_wide,pretty=TRUE),file='edhec_wide.json')
cat(toJSON(edhec_long,pretty=TRUE),file='edhec_long.json')
{
"date" : [
"1997-01-31",
"1997-02-28",
"1997-03-31",
"1997-04-30",
"1997-05-31"
],
"Convertible.Arbitrage" : [
0.0119,
0.0123,
0.0078,
0.0086,
0.0156
],
"CTA.Global" : [
0.0393,
0.0298,
-0.0021,
-0.017,
-0.0015
]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment