Created
October 29, 2013 20:28
-
-
Save ramnathv/7222006 to your computer and use it in GitHub Desktop.
Data Frame to JSON ala Pandas
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
to_json = function(df, orient = "columns", json = T){ | |
dl = as.list(df) | |
dl = switch(orient, | |
columns = dl, | |
records = do.call('zip_vectors_', dl), | |
values = do.call('zip_vectors_', setNames(dl, NULL)) | |
) | |
if (json){ | |
dl = rjson::toJSON(dl) | |
} | |
return(dl) | |
} | |
zip_vectors_ = function(..., names = F){ | |
x = list(...) | |
y = lapply(seq_along(x[[1]]), function(i) lapply(x, pluck_(i))) | |
if (names) names(y) = seq_along(y) | |
return(y) | |
} | |
pluck_ = function (element){ | |
function(x) x[[element]] | |
} | |
df = data.frame( | |
x = c(1, 2), | |
y = c('a', 'b') | |
) | |
to_json(df, orient = 'columns') | |
# {"x":[1,2],"y":["a","b"]} | |
to_json(df, orient = 'records') | |
# [{"x":1,"y":"a"},{"x":2,"y":"b"}] | |
to_json(df, orient = 'values') | |
# [[1,"a"],[2,"b"]] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment