From 979e943c6828a89ea850ec315f4e2e47d6305d92 Mon Sep 17 00:00:00 2001 From: Kun Ren Date: Fri, 28 Mar 2014 19:51:42 +0800 Subject: [PATCH] c2 updated --- data/test1.user.json | 12 ++++++++++++ src/c2.jsonlite.R | 27 +++++++++++++++++++++++++++ 2 files changed, 39 insertions(+) create mode 100644 data/test1.user.json diff --git a/data/test1.user.json b/data/test1.user.json new file mode 100644 index 0000000..03cbcb7 --- /dev/null +++ b/data/test1.user.json @@ -0,0 +1,12 @@ +{ + "sample": 200, + "functions": { + "runif": { + "max": 12 + }, + "rbinom": { + "size": 12 + } + }, + "aggregate": ["mean","sd","median"] +} \ No newline at end of file diff --git a/src/c2.jsonlite.R b/src/c2.jsonlite.R index ac0262e..ec023eb 100644 --- a/src/c2.jsonlite.R +++ b/src/c2.jsonlite.R @@ -9,6 +9,7 @@ library(jsonlite) ### Exampel 1 get.df <- function(json) { + require(jsonlite) profile <- fromJSON(json,simplifyDataFrame = FALSE) message(sprintf("Profile '%s' loaded", profile$title)) rows <- data.frame(lapply(names(profile$functions),function(fun) { @@ -23,3 +24,29 @@ get.df <- function(json) { } df <- get.df("data/test1.json") + +### Example 2: modifyList() + +get.df2 <- function(name,format="data/%s.json",update=".user") { + require(jsonlite) + file.default <- sprintf(format,name) + file.user <- sprintf(format,paste0(name,update)) + profile <- fromJSON(file.default,simplifyDataFrame = FALSE) + if(file.exists(file.user)) { + profile.user <- fromJSON(file.user,simplifyDataFrame = FALSE) + profile <- modifyList(profile,profile.user) + } + str(profile) + message(sprintf("Profile '%s' loaded", profile$title)) + rows <- data.frame(lapply(names(profile$functions),function(fun) { + do.call(fun,c(list(n=profile$sample),profile$functions[[fun]])) + })) + colnames(rows) <- names(profile$functions) + aggs <- data.frame(lapply(profile$aggregate, function(fun) { + apply(rows,MARGIN = 1,FUN = get(fun)) + })) + colnames(aggs) <- profile$aggregate + cbind(rows,aggs) +} + +df <- get.df2("test1")