0

I am trying to recode countries into the Middle East and North Africa (MENA) region in R. Region is not a variable in the dataset but I want to clean my data up and code each country in a region. How do I do this using the dplyr package?

1
  • 1
    Please provide an example of your data set along with the desired output. Also, there is a package available called "rworldmap" that provides this information in a dataset called countryExData. Commented Apr 7, 2022 at 4:20

2 Answers 2

1

As Phil suggested, the data you want may already be curated in the {rworldmap} package. Here's some code to extract what it sounds like you're looking for.

library(tidyverse)

d <- rworldmap::countryExData[,2:4] %>% janitor::clean_names()

d %>% 
  filter(str_detect(epi_regions,pattern = "Middle")) %>% 
  mutate(continent = if_else(str_detect(geo_subregion, "Africa"), "Africa", "Middle East")) %>% 
  select(1, 4)
#>                             country   continent
#> 1              United Arab Emirates Middle East
#> 2                           Armenia Middle East
#> 3                            Cyprus Middle East
#> 4                           Algeria      Africa
#> 5                             Egypt      Africa
#> 6                              Iran Middle East
#> 7                              Iraq Middle East
#> 8                            Israel Middle East
#> 9                            Jordan Middle East
#> 10                           Kuwait Middle East
#> 11                          Lebanon Middle East
#> 12                          Morocco      Africa
#> 13                             Oman Middle East
#> 14                     Saudi Arabia Middle East
#> 15                            Sudan      Africa
#> 16                            Syria Middle East
#> 17                          Tunisia      Africa
#> 18                           Turkey Middle East
#> 19                            Yemen Middle East

Created on 2022-04-07 by the reprex package (v2.0.1)

Sign up to request clarification or add additional context in comments.

Comments

0

If you want to do this manually, you can use fct_collapse from package forcats, this is explained in this tutorial.

library(dplyr)
library(forcats)
dat %>%
  mutate(region = fct_collapse(country,
    MENA = c("Egypt", "Syria", "Lebanon")
  ))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.