My dataframe in R includes specific Patient_IDs
that I need to change for data safety reasons.
They are all named with the first letter of their last name and a six-digit number corresponding to their birth date (e.g., A010590
). I could only find functions in R that replace the whole value (i. e., the whole package "A010590"
to "X"
for example), but I would like to change within each cell the letter to another letter (e.g., A to K) and the numbers to different numbers (e.g., 1 to 5) for all patients, i.e. in all rows of this "Patient_ID" column. (e.g., A010190
would then become K252132
, if A->K, 0->2, 1->5, 5->1, 9->3)
Can anyone help me? Thanks a lot in advance!
CodePudding user response:
You can use stringi::stri_replace_all_fixed
:
library(stringi)
pattern = c("A", "0", "1", "5", "9")
replacement = c("K", "2", "5", "1", "3")
stri_replace_all_fixed("A010590", pattern, replacement, vectorize_all = FALSE)
# [1] "K212132"