Replace NA with specific values

Description

This function replaces (tagged) NA's of a variable, data frame or list of variables with value.

Usage

1
2
3
replace_na(x, value, na.label = NULL, tagged.na = NULL)

replace_na(x, na.label = NULL, tagged.na = NULL) <- value

Arguments

x

Variable (vector), data.frame or list of variables where missing values should be replaced with value.

value

Value that will replace the NA's.

na.label

Optional character vector, used to label the the former NA-value (i.e. adding a labels attribute for value to x).

tagged.na

Optional single character, specifies a tagged_na value that will be replaced by value. Herewith it is possible to replace only specific NA values of x.

Details

While regular NA values can only be completely replaced with a single value, tagged_na allows to differentiate between different qualitative values of NAs. Tagged NAs work exactly like regular R missing values except that they store one additional byte of information: a tag, which is usually a letter ("a" to "z") or character number ("0" to "9"). Therewith it is possible to replace only specific NA values, while other NA values are preserved.

Value

x, where NA's are replaced with value.

Note

Value and variable label attributes (see, for instance, get_labels or set_labels) are preserved.

See Also

set_na for setting NA values, rec for general recoding of variables and recode_to for re-shifting value ranges.

Examples

 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
data(efc)
table(efc$e42dep, useNA = "always")
table(replace_na(efc$e42dep, 99), useNA = "always")

# the original labels
get_labels(replace_na(efc$e42dep, 99))
# NA becomes "99", and is labelled as "former NA"
get_labels(replace_na(efc$e42dep, 99, na.label = "former NA"),
           include.values = "p")

dummy <- list(efc$c82cop1, efc$c83cop2, efc$c84cop3)
# show original distribution
lapply(dummy, table, useNA = "always")
# show variables, NA's replaced with 99
lapply(replace_na(dummy, 99), table, useNA = "always")

library(haven)
x <- labelled(c(1:3, tagged_na("a", "c", "z"), 4:1),
              c("Agreement" = 1, "Disagreement" = 4, "First" = tagged_na("c"),
                "Refused" = tagged_na("a"), "Not home" = tagged_na("z")))
# get current NA values
x
get_na(x)

# replace only the NA, which is tagged as NA(c)
replace_na(x, 2, tagged.na = "c")
get_na(replace_na(x, 2, tagged.na = "c"))

table(x)
table(replace_na(x, 2, tagged.na = "c"))

# tagged NA also works for non-labelled class
# init vector
x <- c(1, 2, 3, 4)
# set values 2 and 3 as NA, will automatically become
# tagged NAs by 'set_na()'.
set_na(x) <- c(2, 3)
# see result
x
# now replace only NA tagged with 2 with value 5
replace_na(x, 5, tagged.na = "2")

Want to suggest features or report bugs for rdrr.io? Use the GitHub issue tracker.