3

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?

severin
  • 2,106
  • 1
  • 17
  • 25

2 Answers2

8

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.

Matthew Plourde
  • 43,932
  • 7
  • 96
  • 113
4

Alternatively, as Justin pointed out:

factor(countries,levels = mapping$country,labels = mapping$iso3)
[1] USA ECU RUS RUS ECU
Levels: ECU RUS USA
joran
  • 169,992
  • 32
  • 429
  • 468
  • Thanks! I accepted this answer because it helped me to realize that I should be using factors for this variable. @Matthews answer works just as well, however. – severin Jun 14 '13 at 14:44