In the 'Auto' dataset, a column has codes for origin of cars. 1 for American, 2 for European, 3 for Japanese. I want to replace the codes with strings. All 1s shall be replaced by 'amer', 2s by 'euro', 3s by 'jap'.
Queries
What's the best way to create key-value pairings in R? (I did this with a list, is there a better way?)
What is the most efficient way to replace values in a dataframe column based on key-value pairings?
Here is a simulation of data:
a = replicate(15, sample(1:3, 1))
a
#> 3 3 3 3 1 2 3 1 3 3 1 3 1 2 3
## Create key-value pairings
origin_code = vector(mode='list', length=3)
names(origin_code) = c(1, 2, 3)
origin_code[[1]] = 'amer'
origin_code[[2]] = 'euro'
origin_code[[3]] = 'jap'
origin_code
#>
$`1`
[1] "amer"
$`2`
[1] "euro"
$`3`
[1] "jap"
## Replace values
<Help needed here>
# I tried the following but got NULL (Why?)
# replace values
b = for (x in unique(a)) {replace(a, a==x, origin_code[x])}
b
#> NULL