Skip to contents

Turn SAS blank strings into proper R NAs.

Usage

convert_blanks_to_na(x)

# S3 method for default
convert_blanks_to_na(x)

# S3 method for character
convert_blanks_to_na(x)

# S3 method for list
convert_blanks_to_na(x)

# S3 method for data.frame
convert_blanks_to_na(x)

Arguments

x

Any R object

Value

An object of the same class as the input

Details

The default methods simply returns its input unchanged. The character method turns every instance of "" into NA_character_ while preserving all attributes. When given a data frame as input the function keeps all non-character columns as is and applies the just described logic to character columns. Once again all attributes such as labels are preserved.

See also

Utilities for Formatting Observations: convert_na_to_blanks(), yn_to_numeric()

Examples

library(tibble)

convert_blanks_to_na(c("a", "b", "", "d", ""))
#> [1] "a" "b" NA  "d" NA 

df <- tibble(
  a = structure(c("a", "b", "", "c"), label = "A"),
  b = structure(c(1, NA, 21, 9), label = "B"),
  c = structure(c(TRUE, FALSE, TRUE, TRUE), label = "C"),
  d = structure(c("", "", "s", "q"), label = "D")
)
print(df)
#> # A tibble: 4 x 4
#>   a         b c     d    
#>   <chr> <dbl> <lgl> <chr>
#> 1 "a"       1 TRUE  ""   
#> 2 "b"      NA FALSE ""   
#> 3 ""       21 TRUE  "s"  
#> 4 "c"       9 TRUE  "q"  
convert_blanks_to_na(df)
#> # A tibble: 4 x 4
#>   a         b c     d    
#>   <chr> <dbl> <lgl> <chr>
#> 1 a         1 TRUE  NA   
#> 2 b        NA FALSE NA   
#> 3 NA       21 TRUE  s    
#> 4 c         9 TRUE  q