/
helpfunctions.R
60 lines (51 loc) · 1.45 KB
/
helpfunctions.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
56
57
58
59
60
# S4 to list object. Not quite sure if this really works in general. You probably
# shouldn't use S4 instances with JSON anyway because you don't know the class
# definition.
S4tolist <- function(x) {
structure(lapply(slotNames(x), slot, object = x), .Names = slotNames(x))
}
# ENCODING TOOLS
# opposite of unname: force list into named list to get key/value json encodings
givename <- function(obj) {
return(structure(obj, names = as.character(names(obj))))
}
# vectorized deparse
deparse_vector <- function(x) {
stopifnot(is.character(x))
vapply(as.list(x), deparse, character(1))
}
# trim whitespace
trim <- function(x) {
gsub("(^[[:space:]]+|[[:space:]]+$)", "", x)
}
# put double quotes around a string
wrapinquotes <- function(x) {
paste("\"", x, "\"", sep = "")
}
# DECODING TOOLS
evaltext <- function(text) {
return(eval(parse(text = text)))
}
null2na <- function(x, unlist = TRUE) {
if (!length(x)) {
if (isTRUE(unlist)) {
return(vector())
} else {
return(list())
}
}
# parse explicitly quoted missing values, unless in the case of character vectors
if (!isTRUE(any(vapply(x, function(y) {
is.character(y) && !(y %in% c("NA", "Inf", "-Inf", "NaN"))
}, logical(1))))) {
missings <- x %in% c("NA", "Inf", "-Inf", "NaN")
x[missings] <- lapply(x[missings], evaltext)
}
# parse 'null' values
x[unlist(sapply(x, is.null))] <- NA
if (isTRUE(unlist)) {
return(unlist(x))
} else {
return(x)
}
}