Home > Back-end >  Mapping all characters into another set of characters in R for a string using list
Mapping all characters into another set of characters in R for a string using list

Time:05-30

How do I efficiently modify a a single string (which is to be part of a column) according to a predefined dictionary (named list) of character mappings?

Suppose I had the mapping:

map <- list('a' = 'u', 'e' = 'i', 'i' = 'o', 'o' = 'a', 'u' = 'e')

And the character vector:

imp_text <- c('aei', 'ou ei', 'iua oe')

I would like to apply some function to imp_text and obtain

c('uio' , 'ae io', 'oeu ai')

Where each character was translated according to the associations defined in map. In the future, map might contain a mapping for the entire alphabet, and imp_text might contain a very large amount of entries. How do I accomplish this? I would prefer a tidyverse approach but anything's welcome.

CodePudding user response:

chartr(paste0(names(map), collapse=""), paste(map, collapse=""), imp_text)
# [1] "uio"    "ae io"  "oeu ai"
  • Related