# NOT RUN {
# 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)
# }
Run the code above in your browser using DataLab