Blaszard
Blaszard

Reputation: 31975

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?

Upvotes: 5

Views: 3205

Answers (3)

Blaszard
Blaszard

Reputation: 31975

I found that this is easily achieved by defining a vector with an attached string, like:

map <- c("s"="Superlative", "d"="Dynamic", "f"="Furious")
df$longCharacter <- map(df$shortCharacter)

This is executed much like a dictionary in Python, in one-line code.

Upvotes: 0

Michael Griffiths
Michael Griffiths

Reputation: 1427

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

Upvotes: 4

aichao
aichao

Reputation: 7445

You can use an environment as a hash table:

dict <- new.env(hash = TRUE, parent = emptyenv(), size = NA)
## insert into hash table
dict[["s"]] <- "Superlative"
dict[["d"]] <- "Dynamic"
dict[["f"]] <- "Furious"
## query using key
key <- "s"
dict[[key]]
##[1] "Superlative"
key2 <- "f"
dict[[key2]]
##[1] "Furious"

Upvotes: 3

Related Questions