Reputation: 31975
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
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
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
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