replace symbols or other character flags

replace_values(x, flag_df, nonflag = NULL, as_numeric = TRUE)

Arguments

x

vector to replace

flag_df

dataframe with first column being the flag and second the replacement value

nonflag

what to do with non-flagged elements

as_numeric

whether to return column as numeric

Details

because of R's coercion rules being somewhat unpredictable regarding character vs factor the behavior of replace_values is to always treat as character data, even if passed in as a factor

See also

unique_non_numerics: to identify which non-numeric values must be replaced before column can be safely coerced to a numeric

Examples

df <- data.frame(ID = 1, DV = c(1, "BQL", ".", 5)) rflags <- data.frame(flag = c("BQL", "."), replacement = -99) df$DVR <- replace_values(df$DV, rflags)
#> converting factor to character before replacement
library(dplyr) df <- df %>% mutate(DVR2 = replace_values(DV, rflags))
#> converting factor to character before replacement
# powerful with unique_non_numerics df <- df %>% mutate(DVR3 = replace_values(DV, data.frame(values = unique_non_numerics(DV), replacement = NA)))
#> converting factor to character before replacement