/
val_labels.R
635 lines (577 loc) · 15.4 KB
/
val_labels.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
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
#' Get / Set value labels
#'
#' @param x A vector or a data.frame
#' @param prefixed Should labels be prefixed with values?
#' @param v A single value.
#' @param value A named vector for `val_labels()` (see [haven::labelled()]) or
#' a character string for `val_label()`. `NULL` to remove the labels (except
#' if `null_action = "labelled"`).
#' For data frames, it could also be a named list with a vector of value
#' labels per variable.
#' @param null_action,.null_action for advanced users, if `value = NULL`,
#' unclass the vector (default) or force/keep `haven_labelled` class
#' (if `null_action = "labelled"`)
#' @return
#' `val_labels()` will return a named vector.
#' `val_label()` will return a single character string.
#' @examples
#' v <- labelled(
#' c(1, 2, 2, 2, 3, 9, 1, 3, 2, NA),
#' c(yes = 1, no = 3, "don't know" = 9)
#' )
#' val_labels(v)
#' val_labels(v, prefixed = TRUE)
#' val_label(v, 2)
#' val_label(v, 2) <- "maybe"
#' v
#' val_label(v, 9) <- NULL
#' v
#' val_labels(v, null_action = "labelled") <- NULL
#' v
#' val_labels(v) <- NULL
#' v
#' @export
val_labels <- function(x, prefixed = FALSE) {
UseMethod("val_labels")
}
#' @export
val_labels.default <- function(x, prefixed = FALSE) {
# return nothing
NULL
}
#' @export
val_labels.haven_labelled <- function(x, prefixed = FALSE) {
labels <- attr(x, "labels", exact = TRUE)
if (prefixed) {
names(labels) <- names_prefixed_by_values(labels)
}
labels
}
#' @export
val_labels.data.frame <- function(x, prefixed = FALSE) {
lapply(x, val_labels, prefixed = prefixed)
}
#' @rdname val_labels
#' @export
`val_labels<-` <- function(
x,
null_action = c("unclass", "labelled"),
value) {
UseMethod("val_labels<-")
}
#' @export
`val_labels<-.default` <- function(
x,
null_action = c("unclass", "labelled"),
value) {
null_action <- match.arg(null_action)
if (!is.null(value) || null_action == "labelled") {
x <- labelled(x, value, label = var_label(x))
}
# otherwise do nothing
x
}
#' @export
`val_labels<-.factor` <- function(
x,
null_action = c("unclass", "labelled"),
value) {
null_action <- match.arg(null_action)
if (!is.null(value) || null_action == "labelled") {
stop("Value labels cannot be applied to factors.")
}
x %>% remove_attributes("labels")
}
#' @export
`val_labels<-.numeric` <- function(
x,
null_action = c("unclass", "labelled"),
value) {
null_action <- match.arg(null_action)
if ((!is.null(value) && length(value) > 0) || null_action == "labelled") {
x <- labelled(x, value, label = var_label(x))
}
x
}
#' @export
`val_labels<-.character` <- function(
x,
null_action = c("unclass", "labelled"),
value) {
null_action <- match.arg(null_action)
if ((!is.null(value) && length(value) > 0) || null_action == "labelled") {
x <- labelled(x, value, label = var_label(x))
}
x
}
#' @export
`val_labels<-.haven_labelled` <- function(
x,
null_action = c("unclass", "labelled"),
value) {
null_action <- match.arg(null_action)
if (length(value) == 0) {
value <- NULL
}
if (is.null(value) && null_action == "unclass") {
x <- unclass(x)
attr(x, "labels") <- NULL
} else {
x <- labelled(x, value, label = var_label(x))
}
x
}
#' @export
`val_labels<-.haven_labelled_spss` <- function(
x,
null_action = c("unclass", "labelled"),
value) {
null_action <- match.arg(null_action)
if (length(value) == 0) {
value <- NULL
}
if (
is.null(value) &&
is.null(attr(x, "na_values")) &&
is.null(attr(x, "na_range")) &&
null_action == "unclass"
) {
x <- unclass(x)
attr(x, "labels") <- NULL
} else {
x <-
labelled_spss(
x,
value,
na_values = attr(x, "na_values"),
na_range = attr(x, "na_range"),
label = var_label(x)
)
}
x
}
#' @export
`val_labels<-.data.frame` <- function(
x,
null_action = c("unclass", "labelled"),
value) {
null_action <- match.arg(null_action)
if (!is.list(value)) {
temp <- as.list(rep(1, ncol(x)))
names(temp) <- names(x)
value <- lapply(temp, function(x) {
x <- value
})
}
if (!all(names(value) %in% names(x))) {
missing_names <- stringr::str_c(
setdiff(names(value), names(x)),
collapse = ", "
)
stop("some variables not found in x:", missing_names)
}
for (var in names(value)) {
if (!is.null(value[[var]])) {
if (mode(x[[var]]) != mode(value[[var]])) {
stop("`x` and `value` must be same type",
call. = FALSE,
domain = "R-labelled"
)
}
if (typeof(x[[var]]) != typeof(value[[var]])) {
mode(value[[var]]) <- typeof(x[[var]])
}
}
}
for (var in names(value)) {
val_labels(x[[var]], null_action = null_action) <- value[[var]]
}
x
}
#' @rdname val_labels
#' @export
val_label <- function(x, v, prefixed = FALSE) {
UseMethod("val_label")
}
#' @export
val_label.default <- function(x, v, prefixed = FALSE) {
if (length(v) != 1) {
stop("`v` should be a single value", call. = FALSE, domain = "R-labelled")
}
# return nothing
NULL
}
#' @export
val_label.haven_labelled <- function(x, v, prefixed = FALSE) {
if (length(v) != 1) {
stop("`v` should be a single value", call. = FALSE, domain = "R-labelled")
}
labels <- val_labels(x, prefixed = prefixed)
if (v %in% labels) {
names(labels)[labels == v]
} else {
NULL
}
}
#' @export
val_label.data.frame <- function(x, v, prefixed = FALSE) {
lapply(x, val_label, v = v, prefixed = prefixed)
}
#' @rdname val_labels
#' @export
`val_label<-` <- function(x, v, null_action = c("unclass", "labelled"), value) {
UseMethod("val_label<-")
}
#' @export
`val_label<-.default` <- function(
x,
v,
null_action = c("unclass", "labelled"),
value) {
if (length(v) != 1) {
stop("`v` should be a single value", call. = FALSE, domain = "R-labelled")
}
if (length(value) > 1) {
stop("`value` should be a single character string or NULL",
call. = FALSE, domain = "R-labelled"
)
}
names(value) <- v
val_labels(x, null_action = null_action) <- value
x
}
#' @export
`val_label<-.haven_labelled` <- function(
x,
v,
null_action = c("unclass", "labelled"),
value) {
if (length(v) != 1) {
stop("`v` should be a single value", call. = FALSE, domain = "R-labelled")
}
if (length(value) > 1) {
stop("`value` should be a single character string or NULL",
call. = FALSE, domain = "R-labelled"
)
}
labels <- val_labels(x)
if (is.null(value)) {
if (v %in% labels) {
labels <- labels[labels != v]
}
} else {
if (v %in% labels) {
names(labels)[labels == v] <- value
} else {
names(v) <- value
labels <- c(labels, v)
}
}
if (length(labels) == 0) {
labels <- NULL
}
val_labels(x, null_action = null_action) <- labels
x
}
#' @export
`val_label<-.numeric` <- `val_label<-.haven_labelled`
#' @export
`val_label<-.character` <- `val_label<-.haven_labelled`
#' @export
`val_label<-.data.frame` <- function(
x,
v,
null_action = c("unclass", "labelled"),
value) {
if (!is.list(value)) {
temp <- as.list(rep(1, ncol(x)))
names(temp) <- names(x)
value <- lapply(temp, function(x) {
x <- value
})
}
value <- value[names(value) %in% names(x)]
for (var in names(value)[]) {
if (!is.character(value[[var]]) && !is.null(value[[var]])) {
stop("`value` should contain only characters or NULL",
call. = FALSE, domain = "R-labelled"
)
}
if (length(value[[var]]) > 1) {
stop("`value` should contain only one string (or NULL) per variable",
call. = FALSE, domain = "R-labelled"
)
}
}
for (var in names(value)) {
val_label(x[[var]], v, null_action = null_action) <- value[[var]]
}
x
}
#' @rdname val_labels
#' @export
get_value_labels <- val_labels
#' @rdname val_labels
#' @param .data a data frame or a vector
#' @param ... name-value pairs of value labels (see examples)
#' @param .labels value labels to be applied to the data.frame,
#' using the same syntax as `value` in `val_labels(df) <- value`.
#' @param .strict should an error be returned if some labels
#' doesn't correspond to a column of `x`?
#' @note
#' `get_value_labels()` is identical to `val_labels()`.
#'
#' `set_value_labels()`, `add_value_labels()` and `remove_value_labels()`
#' could be used with \pkg{dplyr} syntax.
#' While `set_value_labels()` will replace the list of value labels,
#' `add_value_labels()` and `remove_value_labels()` will update that list
#' (see examples).
#'
#' `set_value_labels()` could also be applied to a vector / a data.frame column.
#' In such case, you can provide a vector of value labels using `.labels` or
#' several name-value pairs of value labels (see example).
#' Similarly, `add_value_labels()` and `remove_value_labels()` could also be
#' applied on vectors.
#' @return
#' `set_value_labels()`, `add_value_labels()` and `remove_value_labels()` will
#' return an updated copy of `.data`.
#' @examples
#' if (require(dplyr)) {
#' # setting value labels
#' df <- tibble(s1 = c("M", "M", "F"), s2 = c(1, 1, 2)) %>%
#' set_value_labels(
#' s1 = c(Male = "M", Female = "F"),
#' s2 = c(Yes = 1, No = 2)
#' )
#' val_labels(df)
#'
#' # updating value labels
#' df <- df %>% add_value_labels(s2 = c(Unknown = 9))
#' df$s2
#'
#' # removing a value labels
#' df <- df %>% remove_value_labels(s2 = 9)
#' df$s2
#'
#' # removing all value labels
#' df <- df %>% set_value_labels(s2 = NULL)
#' df$s2
#'
#' # example on a vector
#' v <- 1:4
#' v <- set_value_labels(v, min = 1, max = 4)
#' v
#' v %>% set_value_labels(middle = 3)
#' v %>% set_value_labels(NULL)
#' v %>% set_value_labels(.labels = c(a = 1, b = 2, c = 3, d = 4))
#' v %>% add_value_labels(between = 2)
#' v %>% remove_value_labels(4)
#' }
#' @export
set_value_labels <- function(
.data,
...,
.labels = NA,
.strict = TRUE,
.null_action = c("unclass", "labelled")) {
.null_action <- match.arg(.null_action)
if (!is.data.frame(.data) && !is.atomic(.data)) {
stop(".data should be a data.frame or a vector")
}
# vector case
if (is.atomic(.data)) {
if (!identical(.labels, NA)) {
val_labels(.data, null_action = .null_action) <- .labels
} else {
values <- unlist(rlang::dots_list(...))
val_labels(.data, null_action = .null_action) <- values
}
return(.data)
}
# data.frame case
if (!identical(.labels, NA)) {
if (!.strict) {
.labels <- .labels[intersect(names(.labels), names(.data))]
}
val_labels(.data, null_action = .null_action) <- .labels
}
values <- rlang::dots_list(...)
if (.strict && !all(names(values) %in% names(.data))) {
missing_names <- stringr::str_c(
setdiff(names(values), names(.data)),
collapse = ", "
)
stop("some variables not found in .data: ", missing_names)
}
for (v in intersect(names(values), names(.data))) {
val_labels(.data[[v]], null_action = .null_action) <- values[[v]]
}
.data
}
#' @rdname val_labels
#' @export
add_value_labels <- function(
.data,
...,
.strict = TRUE,
.null_action = c("unclass", "labelled")) {
.null_action <- match.arg(.null_action)
if (!is.data.frame(.data) && !is.atomic(.data)) {
stop(".data should be a data.frame or a vector")
}
# vector case
if (is.atomic(.data)) {
values <- unlist(rlang::dots_list(...))
if (is.null(names(values)) || any(names(values) == "")) {
stop("all arguments should be named")
}
for (v in names(values)) {
val_label(.data, values[[v]], null_action = .null_action) <- v
}
return(.data)
}
# data.frame case
values <- rlang::dots_list(...)
if (.strict && !all(names(values) %in% names(.data))) {
missing_names <- stringr::str_c(
setdiff(names(values), names(.data)),
collapse = ", "
)
stop("some variables not found in .data: ", missing_names)
}
for (v in values) {
if (is.null(names(v)) || any(names(v) == "")) {
stop("all arguments should be named vectors")
}
}
for (v in intersect(names(values), names(.data))) {
for (l in names(values[[v]])) {
val_label(.data[[v]], values[[v]][[l]], null_action = .null_action) <- l
}
}
.data
}
#' @rdname val_labels
#' @export
remove_value_labels <- function(
.data,
...,
.strict = TRUE,
.null_action = c("unclass", "labelled")) {
.null_action <- match.arg(.null_action)
if (!is.data.frame(.data) && !is.atomic(.data)) {
stop(".data should be a data.frame or a vector")
}
# vector case
if (is.atomic(.data)) {
values <- unlist(rlang::dots_list(...))
for (v in values) {
val_label(.data, v, null_action = .null_action) <- NULL
}
return(.data)
}
# data.frame case
values <- rlang::dots_list(...)
if (.strict && !all(names(values) %in% names(.data))) {
missing_names <- stringr::str_c(
setdiff(names(values), names(.data)),
collapse = ", "
)
stop("some variables not found in .data: ", missing_names)
}
for (v in intersect(names(values), names(.data))) {
for (l in values[[v]]) {
val_label(.data[[v]], l, null_action = .null_action) <- NULL
}
}
.data
}
#' Sort value labels
#'
#' Sort value labels according to values or to labels
#'
#' @param x A labelled vector or a data.frame
#' @param according_to According to values or to labels?
#' @param decreasing In decreasing order?
#' @examples
#' v <- labelled(c(1, 2, 3), c(maybe = 2, yes = 1, no = 3))
#' v
#' sort_val_labels(v)
#' sort_val_labels(v, decreasing = TRUE)
#' sort_val_labels(v, "l")
#' sort_val_labels(v, "l", TRUE)
#' @export
sort_val_labels <- function(
x, according_to = c("values", "labels"),
decreasing = FALSE) {
UseMethod("sort_val_labels")
}
#' @export
sort_val_labels.default <- function(
x,
according_to = c("values", "labels"),
decreasing = FALSE) {
# do nothing
x
}
#' @export
sort_val_labels.haven_labelled <- function(
x,
according_to = c("values", "labels"),
decreasing = FALSE) {
according_to <- match.arg(according_to)
labels <- val_labels(x)
if (!is.null(labels)) {
if (according_to == "values") {
labels <- sort_tagged_na(labels, decreasing = decreasing)
}
if (according_to == "labels") {
labels <- labels[order(names(labels), decreasing = decreasing)]
}
val_labels(x) <- labels
}
x
}
#' @export
sort_val_labels.data.frame <- function(
x,
according_to = c("values", "labels"),
decreasing = FALSE) {
x[] <- lapply(x, sort_val_labels,
according_to = according_to,
decreasing = decreasing
)
x
}
#' Turn a named vector into a vector of names prefixed by values
#' @param x vector to be prefixed
#' @examples
#' df <- dplyr::tibble(
#' c1 = labelled(c("M", "M", "F"), c(Male = "M", Female = "F")),
#' c2 = labelled(c(1, 1, 2), c(Yes = 1, No = 2))
#' )
#' val_labels(df$c1)
#' val_labels(df$c1) %>% names_prefixed_by_values()
#' val_labels(df)
#' val_labels(df) %>% names_prefixed_by_values()
#' @export
names_prefixed_by_values <- function(x) {
UseMethod("names_prefixed_by_values")
}
#' @export
names_prefixed_by_values.default <- function(x) {
if (is.null(x)) {
return(NULL)
}
res <- as.character(x)
if (is.double(x)) {
res[is_tagged_na(x)] <- format_tagged_na(x[is_tagged_na(x)])
}
res <- paste0("[", res, "] ", names(x))
names(res) <- names(x)
res
}
#' @export
names_prefixed_by_values.list <- function(x) {
lapply(x, names_prefixed_by_values)
}