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
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
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.