Blaszard Blaszard - 2 months ago 9
R Question

Is it possible to map one string to another using a dictionary-like object in R?

I want to map one string to another in R, using a dictionary-like object as seen in Python. For example, in Python, you can define a dictionary to convert one string to another, like:

d = {"s": "Superlative", "d": "Dynamic", "f": "Furious"}
pd.apply(lambda x: d[x["map_column"]], axis=1)


However, in R, if you want to convert a set of strings in one column to another one based on such mapping, you would end up defining a function that takes a lot of
if else
, like:

mapper <- function(x) {
if (x = "s") {
return ("Superlative")
} else if (x = "d") {
return ("Dynamic")
}...

return("")
}


But I don't like to define such a long, long function. So is it possible to define a dictionary, or more specifically, to get the result with far fewer, one-line (or two) code in R?

Answer

If you're already using the tidyverse, then this is what recode is for in dplyr.

df %>%
    mutate(LongName = recode(ShortName, 
                             s = "Superlative",
                             d = "Dynamic",
                             f = "Furious",
                             `multiple words` = "Use backticks to escape"
                             )
           ) ->
    df