blank_to_na: Replaces blank-ish elements of a factor or character vector...

View source: R/blank_to_na.R

blank_to_naR Documentation

Replaces blank-ish elements of a factor or character vector to NA

Description

Replaces blank-ish elements of a factor or character vector to NA

Usage

blank_to_na(x, na_strings = c("", ".", "NA", "na", "N/A", "n/a", "NaN", "nan"))

Arguments

x

a vector of factor or character or any type

na_strings

case sensitive strings that will be coverted to NA. The function will do a trimws(x,'both') before conversion. If NULL, do only trimws, no conversion to NA.

Value

Returns a vector trimws (always for factor, character) and NA converted (if matching na_strings). Attributes will also be kept ('label','labels', 'value.labels').

References

https://stackoverflow.com/questions/24172111/change-the-blank-cells-to-na

Examples

library(dplyr)
library(tibble)

blank_to_na(x = c("NA", "na", 1, 2, 3))

df <- tibble::tibble(
  a = c("NA", "na", 1, 2, 3),
  b = factor(c("NA", "na", 1, 2, 3))
)
df

levels(df$b)

df2 <- df %>%
  mutate(a = blank_to_na(a),
         b = blank_to_na(b))

df2
levels(df2$b)

emilelatour/lamisc documentation built on April 9, 2024, 10:33 a.m.