forked from jwjw/learnR
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathc2.jsonlite.R
55 lines (47 loc) · 1.58 KB
/
c2.jsonlite.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# {jsonlite} package
library(jsonlite)
## What is JSON
# http://www.json.org/
# https://en.wikipedia.org/wiki/JSON
# http://www.w3schools.com/json/
## Why JSON
## Read/Write JSON in R
### 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) {
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.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")