R/na_if_ext.R

Defines functions na_if_notin na_if_in

Documented in na_if_in na_if_notin

#' Extending na_if to replace multiple values with NA
#'
#' @param x input vector
#' @param y vector of values to replace with NA
#'
#' @return modified vector where all instances from `y` have been replaced with NA
#' @export
#' @importFrom dplyr na_if
#'
#' @examples
#' na_if_in(letters, c("b", "c") )
#' na_if_notin(letters, c("b", "c") )
na_if_in <- function(x, y){
	for(drop in y){
		x = na_if(x, drop)
	}
	if(is.factor(x)) x = factor(x)
	x
}

#' @describeIn na_if_in the logical-not variant
#' @export
na_if_notin <- function(x, y){
	na_if_in(x, na.omit(setdiff(unique(x), y)))
}


## importFrom forcats fct_other fct_drop
## importFrom dplyr na_if
# fct_drop_as_na <- function(x, ...){
# 	stopifnot(is.factor(x))
# 	# ... generate a random string to use for 'other_level'
# 	#other_level = paste(sample(c(letters), size = 10, replace = T), collapse="")
# 	other_level = ".TMPLEVELSHOULDBEDROPPED"
# 	retval = fct_other(x, other_level = other_level, ...)
# 	return( fct_drop( na_if( retval , other_level), other_level ) )
# }
stackcon/rngt documentation built on June 17, 2022, 5:29 p.m.