/
fapply.R
545 lines (424 loc) · 15.3 KB
/
fapply.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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
# Format Application ------------------------------------------------------
#' @title
#' Apply formatting to a vector
#'
#' @description
#' The \code{fapply} function applies formatting to a vector.
#' @details
#' The \code{fapply} function accepts several types of formats: formatting
#' strings, named vectors,
#' vectorized functions, or user-defined formats. It also
#' accepts a formatting list, composed of any of the previous types.
#' The function will first determine the type of format, and then apply
#' the format in the appropriate way. Results are returned as a vector.
#'
#' The function also has parameters for width and justification.
#'
#' Parameters may also be passed as attributes on the vector. See
#' the \code{\link{fattr}} function for additional information on setting
#' formatting attributes.
#'
#' @section Types of Formats:
#' The \code{fapply} function will process any of the following types of
#' formats:
#' \itemize{
#' \item{\strong{Formatting string:} A single string will be interpreted as
#' a formatting string. See the \link{FormattingStrings} documentation for
#' further details.}
#' \item{\strong{Named vector:} A named vector can serve as a lookup list or
#' decode
#' for a vector. You can use a named vector to perform simple
#' lookups on character vectors.}
#' \item{\strong{Format object:} A format object may be created using the
#' \code{\link{value}} function. The format object is included in the
#' \strong{fmtr} package, and is specially designed for data categorization.}
#' \item{\strong{Vectorized formatting function:} A vectorized function
#' provides
#' the most flexibility and power over your formatting. You can use
#' an existing formatting function from any package, or create
#' your own vectorized formatting function using \code{\link[base]{Vectorize}}.}
#' }
#'
#' \code{fapply} will also accept a formatting list, which can contain any
#' number of formats from the above list. To create a formatting list,
#' see the \code{\link{flist}} function.
#' @param x A vector, factor, or list to apply the format to.
#' @param format A format to be applied.
#' @param width The desired character width of the formatted vector. Default
#' value is NULL, meaning the vector will be variable width.
#' @param justify Whether to justify the return vector. Valid values are
#' 'left', 'right', 'center', 'centre', or 'none'.
#' @return A vector of formatted values.
#' @seealso \code{\link{fcat}} to create a format catalog,
#' \code{\link{value}} to define a format,
#' \code{\link{fattr}} to easily set the formatting attributes of a vector,
#' and \code{\link{flist}} to define a formatting list. Also see
#' \code{\link{fdata}} to apply formats to an entire data frame, and
#' \link{FormattingStrings} for how to define a formatting string.
#' @import common
#' @export
#' @examples
#' ## Example 1: Formatting string ##
#' v1 <- c(1.235, 8.363, 5.954, 2.465)
#'
#' # Apply string format.
#' fapply(v1, "%.1f")
#'
#'
#' ## Example 2: Named vector ##
#' # Set up vector
#' v2 <- c("A", "B", "C", "B")
#'
#' # Set up named vector for formatting
#' fmt2 <- c(A = "Vector Label A", B = "Vector Label B", C = "Vector Label C")
#'
#' # Apply format to vector
#' fapply(v2, fmt2)
#'
#'
#' ## Example 3: User-defined format ##
#' # Define format
#' fmt3 <- value(condition(x == "A", "Format Label A"),
#' condition(x == "B", "Format Label B"),
#' condition(TRUE, "Format Other"))
#'
#' # Apply format to vector
#' fapply(v2, fmt3)
#'
#'
#' ## Example 4: Formatting function ##
#' # Set up vectorized function
#' fmt4 <- Vectorize(function(x) {
#'
#' if (x %in% c("A", "B"))
#' ret <- paste("Function Label", x)
#' else
#' ret <- "Function Other"
#'
#' return(ret)
#' })
#'
#' # Apply format to vector
#' fapply(v2, fmt4)
#'
#'
#' ## Example 5: Formatting List - Row Type ##
#' # Set up data
#' # Notice each row has a different data type
#' v3 <- list(2841.258, "H", Sys.Date(),
#' "L", Sys.Date() + 60, 1382.8865)
#' v4 <- c("int", "char", "date", "char", "date", "int")
#'
#' # Create formatting list
#' lst <- flist(type = "row", lookup = v4,
#' int = function(x) format(x, digits = 2, nsmall = 1,
#' big.mark=","),
#' char = value(condition(x == "H", "High"),
#' condition(x == "L", "Low"),
#' condition(TRUE, "NA")),
#' date = "%d%b%Y")
#'
#' # Apply formatting list to vector
#' fapply(v3, lst)
#'
#'
#' ## Example 6: Formatting List - Column Type ##
#' # Set up data
#' v5 <- c(Sys.Date(), Sys.Date() + 30, Sys.Date() + 60)
#' v5
#'
#' # Create formatting list
#' lst <- flist("%B", "This month is: %s", type = "column")
#'
#' # Apply formatting list to vector
#' fapply(v5, lst)
fapply <- function(x, format = NULL, width = NULL, justify = NULL) {
# Get attribute values if available
if (is.null(format) & is.null(attr(x, "format", exact = TRUE)) == FALSE)
format <- attr(x, "format", exact = TRUE)
if (is.null(width) & is.null(attr(x, "width", exact = TRUE)) == FALSE)
width <- attr(x, "width", exact = TRUE)
if (is.null(justify) & is.null(attr(x, "justify", exact = TRUE)) == FALSE)
justify <- attr(x, "justify", exact = TRUE)
# Parameter checks - Date values messing up this check
# if (!is.vector(x) & !is.factor(x) & !is.list(x)) {
#
# stop("Invalid value for parameter x. Must be a vector, factor, or list.")
# }
if (!is.null(format)) {
if (!any(class(format) %in% c("NULL", "character", "fmt", "numeric", "integer",
"fmt_lst", "function")))
stop(paste0("class of format parameter value is invalid: ",
class(format)))
}
if (!is.null(width)) {
if (is.numeric(width) == FALSE)
stop("width parameter must be numeric.")
if (width <= 0)
stop("width parameter must be a positive integer.")
}
if (!is.null(justify)) {
if (!justify %in% c("left", "right", "center", "centre", "none"))
stop(paste("justify parameter is invalid. Valid values are 'left',",
"'right', 'center', 'centre', or 'none'."))
}
ret <- NULL
# Perform different operations depending on type of format
if (is.vector(format) & is.list(format) == FALSE) {
# If format is a single string, call format_vector to deal with it
if (length(format) == 1)
ret <- format_vector(x, format)
else {
if (length(names(format)) == 0) {
stop("Vector formats are required to be named.")
} else {
# For named vectors, perform lookup
if (all(class(format) == "character"))
ret <- lkup(x, format)
else
ret <- format[x]
names(ret) <- NULL # Names not needed and mess up stuff
}
}
}
else if (is.function(format)) {
# For format function, execute it as is
ret <- do.call(format, list(x))
names(ret) <- NULL # Names not needed and mess up stuff
} else if (is.format(format)) {
# For format class, apply to vector using eval_conditions function
ret <- mapply(eval_conditions, x, MoreArgs = list(conds = format))
names(ret) <- NULL # Names not needed and mess up stuff
if (!is.null(attr(format, "as.factor"))) {
if (attr(format, "as.factor") == TRUE) {
ret <- factor(ret, levels = labels(format), ordered = TRUE)
}
}
} else if (is.flist(format)) {
# For flist class, call row or column functions as appropriate
if (format$type == "row")
ret <- flist_row_apply(format, x)
else
ret <- flist_column_apply(format, x)
} else if (is.null(format)) {
# if no format, do nothing
ret <- x
} else
stop(paste0("format parameter must be a vector, function, ",
"user-defined format, or list."))
# Justify and set width once other formatting is complete
ret <- justify_vector(ret, width, justify)
return(ret)
}
#' @title
#' Apply formatting to two vectors
#' @description
#' The \code{fapply2} function applies formatting to two different vectors, and
#' combines them into a single vector. This function is useful in cases
#' where your data is in two different variables, and you would like them
#' displayed as a single column for reporting purposes. For example, if you
#' wish to create one column to display mean and standard deviation.
#' @details
#' The \code{fapply2} function works nearly the same as \code{\link{fapply}}.
#' The difference is it has parameters for two vectors and formats instead of one.
#' The output of the function
#' is a single vector. The function essentially calls \code{\link{fapply}}
#' on each vector and pastes them together afterwards.
#'
#' There is an additional \code{sep} parameter so you can
#' define a separator between the two formatted values.
#' The \code{width} and \code{justify} parameters
#' will apply to the single vector result. The function will also
#' pick up format attributes on the supplied vectors.
#'
#' The \code{fapply2} function accepts any of the format types
#' that \code{\link{fapply}} accepts.
#' See \code{\link{fapply}} for additional information on the types
#' of formats that can be applied.
#'
#' Parameters may also be passed as attributes on the vector. See
#' the \code{\link{fattr}} function for additional information on setting
#' formatting attributes.
#'
#' @param x1 A vector, factor, or list to apply the format1 to.
#' @param x2 A second vector, factor, or list to which format2 will be applied.
#' @param format1 A format to be applied to the first input.
#' @param format2 A format to be applied to the second input.
#' @param sep A separator to use between the two formatted values. Default
#' is a single blank space (" ").
#' @param width The desired character width of the formatted vector. Default
#' value is NULL, meaning the vector will be variable width.
#' @param justify Whether to justify the return vector. Valid values are
#' 'left', 'right', 'center', 'centre', or 'none'.
#' @return A vector of formatted values.
#' @seealso \code{\link{fapply}} to format a single input,
#' \code{\link{fcat}} to create a format catalog,
#' \code{\link{value}} to define a format,
#' \code{\link{fattr}} to easily set the formatting attributes of a vector,
#' and \code{\link{flist}} to define a formatting list. Also see
#' \code{\link{fdata}} to apply formats to an entire data frame, and
#' \link{FormattingStrings} for how to define a formatting string.
#' @export
#' @examples
#' # Create sample data
#' dt <- c(2.1, 5, 6, 9, 2, 7, 3)
#'
#' # Calculate mean and standard deviation
#' v1 <- mean(dt)
#' v2 <- sd(dt)
#'
#' # Apply formats and combine
#' fapply2(v1, v2, "%.1f", "(%.2f)")
#' # [1] "4.9 (2.66)"
fapply2 <- function(x1, x2, format1 = NULL, format2 = NULL, sep = " ",
width = NULL, justify = NULL) {
res1 <- fapply(x1, format1)
res2 <- fapply(x2, format2)
ret <- paste0(res1, sep, res2)
if (!is.null(width) | !is.null(justify))
ret <- justify_vector(ret, width, justify)
return(ret)
}
# Utilities ---------------------------------------------------------------
#' @noRd
eval_conditions <- function(x, conds) {
# Default to the value itself
ret <- x
# Check all conditions
for(cond in conds) {
tmp <- eval(cond[["expression"]])
if (!is.na(tmp) & !is.null(tmp)) {
if (tmp) {
ret <- format_vector(x, cond[["label"]], udfmt = TRUE)
break()
}
}
}
return(ret)
}
eval_conditions_back <- function(x, conds) {
# Default to the value itself
ret <- x
# Check all conditions
for(cond in conds) {
tmp <- eval(cond[["expression"]])
if (!is.na(tmp) & !is.null(tmp)) {
if (tmp) {
ret <- cond[["label"]]
break()
}
}
}
return(ret)
}
#' @noRd
format_vector <- function(x, fmt, udfmt = FALSE) {
if ("character" %in% class(fmt)) {
if (any(class(x) %in% c("Date", "POSIXt"))) {
# For dates, call format
if (udfmt == TRUE) {
ret <- tryCatch({suppressWarnings(format(x, format = fmt))},
error = function(cond) {fmt})
} else {
ret <- format(x, format = fmt)
}
} else if (any(class(x) %in% c("numeric", "character", "integer"))) {
# For numerics, call sprintf
if (udfmt == TRUE) {
ret <- tryCatch({suppressWarnings(sprintf(fmt, x))},
error = function(cond) {fmt})
} else {
ret <- sprintf(fmt, x)
}
# Find NA strings
nas <- ret == "NA"
# Turn NA strings back into real NA
ret <- replace(ret, nas, NA)
} else {
ret <- fmt
}
} else if ("function" %in% class(fmt)) {
ret <- fmt(x)
} else if (any(class(fmt) %in% c("Date", "POSIXt"))) {
ret <- as.Date(fmt)
} else {
ret <- fmt
}
return(ret)
}
#' @noRd
format_vector_back <- function(x, fmt) {
if (any(class(x) %in% c("Date", "POSIXt"))) {
# For dates, call format
ret <- format(x, format = fmt)
} else if (any(class(x) %in% c("numeric", "character", "integer"))) {
# For numerics, call sprintf
ret <- sprintf(fmt, x)
# Find NA strings
nas <- ret == "NA"
# Turn NA strings back into real NA
ret <- replace(ret, nas, NA)
}
return(ret)
}
#' @noRd
justify_vector <- function(x, width = NULL, justify = NULL) {
if (is.null(width) & is.null(justify)) {
# If no justification requested, just return the vector
ret <- x
} else {
# Convert American Spelling to Kiwi spelling
jst <- justify
if (is.null(justify) == FALSE) {
if (justify == "center")
jst <- "centre"
}
# Convert to character if necessary so justification will work
if (is.null(justify) == FALSE & any(class(x) %in% c("integer", "numeric"))){
ret <- format(as.character(x), width = width, justify = jst)
} else if (any(class(x) %in% c("Date", "POSIXt")))
ret <- format(as.character(x), width = width, justify = jst)
else
ret <- format(x, width = width, justify = jst)
}
return(ret)
}
#' @noRd
flist_row_apply <- function(lst, vect) {
# Intitialize
ret <- c()
fmts <- list()
# Lookup vs. Order type
if (!is.null(lst$lookup)) {
fmts <- lst$formats[lst$lookup]
} else {
if (length(vect) %% length(lst) != 0 )
message("NOTE: format list is not a multiple of input vector")
fmts <- rep(lst$formats, length.out = length(vect))
}
# Apply format list to vector values
for (i in seq_along(vect)) {
ret[[i]] <- fapply(vect[[i]][1], fmts[[i]])
}
# Unlist if requested
if (lst$simplify == TRUE)
ret <- unlist(ret)
return(ret)
}
#' @noRd
flist_column_apply <- function(lst, vect) {
# Initialize
ret <- vect
fmts <- lst$formats
# Apply formats to vector in order
for (i in seq_along(fmts)) {
ret <- fapply(ret, fmts[[i]])
}
# Unlist if requested
if(lst$simplify == TRUE)
ret <- unlist(ret)
else if (lst$simplify == FALSE & typeof(ret) != "list")
ret <- as.list(ret)
return(ret)
}
# Testing -----------------------------------------------------------------