R - replace all values in a dataframe column as per a key-value pair

Viewed 443

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

  1. What's the best way to create key-value pairings in R? (I did this with a list, is there a better way?)

  2. 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
1 Answers

As the a is a numeric value, it can be used as index

unlist(origin_code[a], use.names = FALSE)
#[1] "jap"  "jap"  "jap"  "jap"  "amer" "euro" "jap"  "amer" "jap"  "jap"  "amer" "jap"  "amer" "euro" "jap" 

If the names of the list and the 'a' are not numeric, then can use match

unlist(origin_code[match(a, names(origin_code))], use.names = FALSE)

Or can also do this with named vector

unname(unlist(origin_code)[as.character(a)])

In the OP's code, we could make a simple change

b <- a
for(x in unique(a))  b <- replace(b, b == x, origin_code[[x]])
b

data

a <- c(3, 3, 3, 3, 1, 2, 3, 1, 3, 3, 1, 3, 1, 2, 3)
Related