Elements of zero-length are converted to NAs. Can force coercion to an optionally-specified data type.

The function has two parts. First, it uses dplyr::na_if(x, ""). Second, it (optionally) coerces to the desired data type.

replace_with_nas(x, return_type = NULL)

Arguments

x

An array of values. It is temporarily coerced to a string. Required

return_type

Data type of returned vector. Optional

Value

An array of values with NAs.

Details

If return_type is missing, returned data type will match input. Supports coercion to integer, numeric, character, logical, and Date vectors.

If return_type=logical, a logical vector will be returned if x contains only blanks and the characters "0" and "1".

Note

Contact the package author if you'd like the function generalized so that additional values (other that "") are converted to NAs.

Author

Will Beasley

Examples

library(OuhscMunge) #Load the package into the current R session.
replace_with_nas(c("a", "b", "", "d", ""))
#> [1] "a" "b" NA  "d" NA 
replace_with_nas(c("a", "b", "", "d", ""), return_type="character")
#> [1] "a" "b" NA  "d" NA 

replace_with_nas(c(1, 2, "", "", 5), return_type="character")
#> [1] "1" "2" NA  NA  "5"
replace_with_nas(c(1, 2, "", "", 5)) #Equivalent to previous line.
#> [1] "1" "2" NA  NA  "5"
replace_with_nas(c(1, 2, "", "", 5), return_type="integer")
#> [1]  1  2 NA NA  5
replace_with_nas(c(1, 2, "", "", 5), return_type="numeric")
#> [1]  1  2 NA NA  5

replace_with_nas(c("2011-02-03", "", "", "2011-02-24"), return_type="Date")
#> [1] "2011-02-03" NA           NA           "2011-02-24"
replace_with_nas(c("T", "", "", "F", "FALSE", "", "TRUE"), return_type="logical")
#> [1]  TRUE    NA    NA FALSE FALSE    NA  TRUE
replace_with_nas(c("1", "", "", "0", "0"    , "", "1")   , return_type="logical")
#> [1]  TRUE    NA    NA FALSE FALSE    NA  TRUE