R Find character typos and replace with numbers from data frame key

  Kiến thức lập trình

I have manually entered numerical data for which it appears that some numbers were accidentally entered as their “shifted” character value. For example a 9 was entered as “(“. These typos are embedded within a string of other numbers.

I know how to use gsub to find a character and replace it with another character, but how do I search over all the entries in mydata_observed for any of the characters in my_key$find_this and replace that character with the corresponding value in my_key$replace_with?

my_data_desired contains the desired cleaned output.

I am interested in a base R solution.

my_key <- data.frame(
  find_this = c(")", "!", "@", "#", "$", "%", "^", "&", "*", "("),
  replace_with = c("0", "1", "2", "3", "4", "5", "6", "7", "8", "9")
)
my_data_observed <- c("99582", "9(593", "98423", "984@)")
my_data_desired <- c("99582", "99593", "98423", "98420")

LEAVE A COMMENT