-
Notifications
You must be signed in to change notification settings - Fork 116
/
Copy pathzap_missing.R
63 lines (55 loc) · 1.16 KB
/
zap_missing.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
#' Zap special missings to regular R missings
#'
#' This is useful if you want to convert tagged missing values from SAS or
#' Stata, or user-defined missings from SPSS, to regular R `NA`.
#'
#' @param x A vector or data frame
#' @export
#' @examples
#' x1 <- labelled(
#' c(1, 5, tagged_na("a", "b")),
#' c(Unknown = tagged_na("a"), Refused = tagged_na("b"))
#' )
#' x1
#' zap_missing(x1)
#'
#' x2 <- labelled_spss(
#' c(1, 2, 1, 99),
#' c(missing = 99),
#' na_value = 99
#' )
#' x2
#' zap_missing(x2)
#'
#' # You can also apply to data frames
#' df <- tibble::tibble(x1, x2, y = 4:1)
#' df
#' zap_missing(df)
zap_missing <- function(x) {
UseMethod("zap_missing")
}
#' @export
zap_missing.default <- function(x) {
x
}
#' @export
zap_missing.haven_labelled <- function(x) {
x[is.na(x)] <- NA
labels <- attr(x, "labels")
labels <- labels[!is.na(labels)]
attr(x, "labels") <- labels
x
}
#' @export
zap_missing.haven_labelled_spss <- function(x) {
x[is.na(x)] <- NA
attr(x, "na_values") <- NULL
attr(x, "na_range") <- NULL
class(x) <- "haven_labelled"
x
}
#' @export
zap_missing.data.frame <- function(x) {
x[] <- lapply(x, zap_missing)
x
}