replace symbols or other character flags
replace_values(x, flag_df, nonflag = NULL, as_numeric = TRUE)
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 |
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
unique_non_numerics
: to identify which non-numeric values must
be replaced before column can be safely coerced to a numeric
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)#>#># powerful with unique_non_numerics df <- df %>% mutate(DVR3 = replace_values(DV, data.frame(values = unique_non_numerics(DV), replacement = NA)))#>