if_na | R Documentation |
if_na
replaces NA values in vector/data.frame/matrix/list with
supplied value. For single value argument label can be provided with
label
argument. If replacement value is vector then if_na
uses
for replacement values from appropriate positions. An opposite operation is na_if
.
na_if
replaces values with NA in
vector/data.frame/matrix/list. Another alias for this is mis_val
.
valid
returns logical vector which indicate the presence of at
least one not-NA value in row. For vector or single column data.frame result
is the same as with complete.cases. There is a special case
for data.frame of class dichotomy
. In this case result indicate the
presence of at least one 1 in a row.
if_na(x, value, label = NULL)
if_na(x, label = NULL) <- value
x %if_na% value
na_if(x, value, with_labels = FALSE)
na_if(x, with_labels = FALSE) <- value
x %na_if% value
mis_val(x, value, with_labels = FALSE)
mis_val(x, with_labels = FALSE) <- value
valid(x)
x |
vector/matrix/data.frame/list |
value |
single value, vector of the same length as number of rows in
|
label |
a character of length 1. Label for |
with_labels |
logical. FALSE by default. Should we also remove labels of values which we recode to NA? |
An object of class character
of length 1.
object of the same form and class as x
. valid
returns logical vector.
# simple case
a = c(NA, 2, 3, 4, NA)
if_na(a, 99)
# the same result
a %if_na% 99
# with label
a = c(NA, 2, 3, 4, NA)
if_na(a, 99, label = "Hard to say")
# in-place replacement. The same result:
if_na(a, label = "Hard to say") = 99
a # c(99, 2, 3, 4, 99)
# replacement with values from other variable
a = c(NA, 2, 3, 4, NA)
b = 1:5
if_na(a, b)
# replacement with group means
# make data.frame
set.seed(123)
group = sample(1:3, 30, replace = TRUE)
param = runif(30)
param[sample(30, 10)] = NA # place 10 NA's
df = data.frame(group, param)
# replace NA's with group means
if_na(df$param) = window_fun(df$param, df$group, mean_col)
df
######################
### na_if examples ###
######################
a = c(1:5, 99)
# 99 to NA
na_if(a, 99) # c(1:5, NA)
a %na_if% 99 # same result
# values which greater than 4 to NA
na_if(a, gt(4)) # c(1:4, NA, NA)
# alias 'mis_val', with_labels = TRUE
a = c(1, 1, 2, 2, 99)
val_lab(a) = c(Yes = 1, No = 2, "Hard to say" = 99)
mis_val(a, 99, with_labels = TRUE)
set.seed(123)
dfs = data.frame(
a = c("bad value", "bad value", "good value", "good value", "good value"),
b = runif(5)
)
# rows with 'bad value' will be filled with NA
# logical argument and recycling by columns
na_if(dfs, dfs$a=="bad value")
a = rnorm(50)
# values greater than 1 or less than -1 will be set to NA
# special functions usage
na_if(a, lt(-1) | gt(1))
# values inside [-1, 1] to NA
na_if(a, -1 %thru% 1)
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.