View source: R/convert_na_to.R
convert_na_to | R Documentation |
Replace missing values in a variable or a data frame.
convert_na_to(x, ...)
## S3 method for class 'numeric'
convert_na_to(x, replacement = NULL, verbose = TRUE, ...)
## S3 method for class 'character'
convert_na_to(x, replacement = NULL, verbose = TRUE, ...)
## S3 method for class 'data.frame'
convert_na_to(
x,
select = NULL,
exclude = NULL,
replacement = NULL,
replace_num = replacement,
replace_char = replacement,
replace_fac = replacement,
ignore_case = FALSE,
regex = FALSE,
verbose = TRUE,
...
)
x |
A numeric, factor, or character vector, or a data frame. |
... |
Not used. |
replacement |
Numeric or character value that will be used to
replace |
verbose |
Toggle warnings. |
select |
Variables that will be included when performing the required tasks. Can be either
If |
exclude |
See |
replace_num |
Value to replace |
replace_char |
Value to replace |
replace_fac |
Value to replace |
ignore_case |
Logical, if |
regex |
Logical, if |
x
, where NA
values are replaced by replacement
.
select
argumentFor most functions that have a select
argument (including this function),
the complete input data frame is returned, even when select
only selects
a range of variables. That is, the function is only applied to those variables
that have a match in select
, while all other variables remain unchanged.
In other words: for this function, select
will not omit any non-included
variables, so that the returned data frame will include all variables
from the input data frame.
# Convert NA to 0 in a numeric vector
convert_na_to(
c(9, 3, NA, 2, 3, 1, NA, 8),
replacement = 0
)
# Convert NA to "missing" in a character vector
convert_na_to(
c("a", NA, "d", "z", NA, "t"),
replacement = "missing"
)
### For data frames
test_df <- data.frame(
x = c(1, 2, NA),
x2 = c(4, 5, NA),
y = c("a", "b", NA)
)
# Convert all NA to 0 in numeric variables, and all NA to "missing" in
# character variables
convert_na_to(
test_df,
replace_num = 0,
replace_char = "missing"
)
# Convert a specific variable in the data frame
convert_na_to(
test_df,
replace_num = 0,
replace_char = "missing",
select = "x"
)
# Convert all variables starting with "x"
convert_na_to(
test_df,
replace_num = 0,
replace_char = "missing",
select = starts_with("x")
)
# Convert NA to 1 in variable 'x2' and to 0 in all other numeric
# variables
convert_na_to(
test_df,
replace_num = 0,
select = list(x2 = 1)
)
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.