0
regions_numbers <- c(2,9,21,142,150,419)
regions_names <- c("Oceania", "Africa", "North America", "Asia", "Europe", "Latin America")

I need to replace the numbers with their corresponding region name but I'm unsure what code to use

stefan
  • 90,330
  • 6
  • 25
  • 51
  • To clarify, you are saying you want to replace the number "2" with "Oceania". Or say, "150" with "Europe". So if then, we introduce a new vector with say `eg<-c(142,142,142)` you want a new vector where instead it says `c("Asia","Asia","Asia")` ? – Luca Pontiggia Apr 16 '20 at 17:57
  • yes, exactly. each of those numbers corresponds to the respective region – Cristina Russo Apr 16 '20 at 18:00
  • The numbers are in a column called "Region." I want to replace the numbers in the column with the corresponding names – Cristina Russo Apr 16 '20 at 18:10

2 Answers2

0

I'm sure there are many ways, but off the top of my head I would resort to using dataframes. That way we can do things like left_join which does the mapping (similar to vlookup) in excel.

We start off by creating a mapping dataframe:

df_region = data.frame(regions_numbers = c(2,9,21,142,150,419),
                      regions_names = c("Oceania", "Africa", "North America", "Asia", "Europe", "Latin America"))

Now, we can do the mapping, by converting any future vector into a dataframe as well:

new_region_numbers = data.frame(regions_numbers  = sample(c(2,9,21,142,150,419),10,replace = TRUE))

The sample just gives me a random set of region_numbers. Now by using left_join, we easily get the mapping you want:

new_region_names =new_region_numbers %>% 
  left_join(df_region, by = c("regions_numbers" = "regions_numbers"))

with output:

  regions_numbers regions_names
1              142          Asia
2              142          Asia
3              150        Europe
4                9        Africa
5              150        Europe
6              150        Europe
7               21 North America
8               21 North America
9              419 Latin America
10             150        Europe

and if you only want the vector then you can select it by saying:

new_names_only = new_region_names$regions_names 

That's one way of doing it. I'm sure there a more "inbuilt" functions for doing these kinds of mapping. But can't think of any at the moment.

0

Another simple way, tidy way...

sample_vec <- sample(regions_numbers, 20, replace = TRUE)
recode(sample_vec, "2" = "Oceania", "9" = "Africa", "21" = "North America",
           "142" = "Asia", "150" = "Europe", "419" = "Latin America")

Useful link.

nikn8
  • 1,016
  • 8
  • 23