severin
severin

Reputation: 2126

Replace many strings by their counterparts according to a mapping

I have a vector of strings (e.g. country names), and a mapping of those strings to other strings (e.g. a mapping of country names to iso codes).

countries = c('United States', 'Ecuador', 'Russia', 'Russia', 'Ecuador')
mapping = data.frame(country = c('Ecuador', 'Russia', 'United States'),
                     iso3 = c('ECU', 'RUS', 'USA'))

How can I replace all occurences of country names in countries by the respective iso codes according to mapping?

Upvotes: 3

Views: 2005

Answers (2)

joran
joran

Reputation: 173677

Alternatively, as Justin pointed out:

factor(countries,levels = mapping$country,labels = mapping$iso3)
[1] USA ECU RUS RUS ECU
Levels: ECU RUS USA

Upvotes: 4

Matthew Plourde
Matthew Plourde

Reputation: 44614

This is one way:

with(mapping, iso3[match(countries, country)])
# [1] USA ECU RUS RUS ECU
# Levels: ECU RUS USA

Wrap this in as.character to the result as a character vector.

Upvotes: 8

Related Questions