Renaming names in a dataset with commas and fullstops - r

I am trying to rename some countries in my data but I seem to be having an issue with one. I wish to rename these following countries but I get an error when trying to rename 'Egypt, Arab Rep.' to `Egypt'
data
Country_Name value
Egypt, Arab Rep. 2192
Syrian Arab Republic 4998
Turkiye 8230
code used to rename
data = data %>% rename(Egypt = "Egypt, Arab Rep.") %>% rename(Syria = "Syrian Arab Republic") %>% rename(Turkey = "Turkiye")
error message received
`Error in `stop_subscript()`:
! Can't rename columns that don't exist.
✖ Column_Name `Egypt, Arab Rep.` doesn't exist.`

A dplyr way of doing this would be using the case_when function
library(dplyr)
df <- data.frame(Country = c("Egypt, Arab Rep.", "Syrian Arab Republic", "Turkiye"),
value = c(2192, 4998, 8230))
df <- df %>%
dplyr::mutate(Country = dplyr::case_when(
Country == "Egypt, Arab Rep." ~ "Egypt",
Country == "Syrian Arab Republic" ~ "Syria",
TRUE ~ Country
))
RESULT:
Country value
1 Egypt 2192
2 Syria 4998
3 Turkiye 8230

Related

How to group a column with character values in a new column in r

I have a data set with countries column, I want to create a new column and classify the countries into the following categories (first world, second world, third world) countries.
I'm relatively new to R and I'm finding it difficult to find a proper function that deals with characters!
My dataset contains the countries like this, and I have three vectors with a list of countries as shown below:
nt_final_table$`Country name`
#[1] "Finland" "Denmark" "Switzerland"
#[4] "Iceland" "Netherlands" "Norway"
#[7] "Sweden" "Luxembourg" "New Zealand"
#[10] "Austria" "Australia" "Israel"
first_world_countries <- c("Australia","Austria","Belgium","Canada","Denmark","France","Germany","Greece","Iceland","Ireland","Israel","Italy","Japan","Luxembourg","Netherlands","New Zealand","Norway","Portugal","South Korea",
"Spain","Sweden","Switzerland","Turkey","United Kingdom","USA")
Second_world_countries <- c("Albania","Armenia","Azerbaijan","Belarus","Bosnia and Herzegovina","Bulgaria","China","Croatia","Cuba","Czech Republic","EastGermany","Estonia","Georgia","Hungary","Kazakhstan","Kyrgyzstan","Laos","Poland","Romania","Russia","Serbia","Slovakia","Slovenia","Tajikistan","Turkmenistan","Ukraine","Uzbekistan","Vietnam")
Third_world_countries <- ("Somalia","Niger","South Sudan")
I would want a new column that contains the following values :
First World, Second World, Third World based on the Country name column
Any help would be appreciated!
Thanks!
Here are 2 ways you could do this.
Using dplyr package
You could use case_when from the dplyr package to do this.
library(dplyr)
country_name <-c("Finland", "Denmark", "Switzerland","Iceland", "Netherlands", "Norway", "Sweden", "Luxembourg", "New Zealand",
"Austria", "Australia", "Israel")
nt_final_table <- data.frame(country_name)
first_world_countries <- c("Australia","Austria","Belgium","Canada","Denmark","France","Germany","Greece","Iceland","Ireland","Israel","Italy","Japan","Luxembourg","Netherlands","New Zealand","Norway","Portugal","South Korea", "Spain","Sweden","Switzerland","Turkey","United Kingdom","USA")
second_world_countries <- c("Albania","Armenia","Azerbaijan","Belarus","Bosnia and Herzegovina","Bulgaria","China","Croatia","Cuba","Czech Republic","EastGermany","Estonia","Georgia","Hungary","Kazakhstan","Kyrgyzstan","Laos","Poland","Romania","Russia","Serbia","Slovakia","Slovenia","Tajikistan","Turkmenistan","Ukraine","Uzbekistan","Vietnam")
third_world_countries <- c("Somalia","Niger","South Sudan")
nt_final_table_categorized <- nt_final_table %>% mutate(category = case_when(country_name %in% first_world_countries ~ "First",
country_name %in% second_world_countries ~ "Second",
country_name %in% third_world_countries ~ "Third",
TRUE ~"Not listed"))
nt_final_table_categorized
Sample output
country_name category
1 Finland Not listed
2 Denmark First
3 Switzerland First
4 Iceland First
5 Netherlands First
6 Norway First
7 Sweden First
8 Luxembourg First
9 New Zealand First
10 Austria First
11 Australia First
12 Israel First
Using base R
In base R we could create a data frame that lists the countries and their category then use merge to perform a left-join on the 2 dataframes.
country_name <-c("Finland", "Denmark", "Switzerland","Iceland", "Netherlands", "Norway", "Sweden", "Luxembourg", "New Zealand",
"Austria", "Australia", "Israel")
nt_final_table <- data.frame(country_name)
first_world_countries <- c("Australia","Austria","Belgium","Canada","Denmark","France","Germany","Greece","Iceland","Ireland","Israel","Italy","Japan","Luxembourg","Netherlands","New Zealand","Norway","Portugal","South Korea", "Spain","Sweden","Switzerland","Turkey","United Kingdom","USA")
second_world_countries <- c("Albania","Armenia","Azerbaijan","Belarus","Bosnia and Herzegovina","Bulgaria","China","Croatia","Cuba","Czech Republic","EastGermany","Estonia","Georgia","Hungary","Kazakhstan","Kyrgyzstan","Laos","Poland","Romania","Russia","Serbia","Slovakia","Slovenia","Tajikistan","Turkmenistan","Ukraine","Uzbekistan","Vietnam")
third_world_countries <- c("Somalia","Niger","South Sudan")
country_name <- c(first_world_countries,second_world_countries,third_world_countries)
categories <- c(rep("First", length(first_world_countries)),
rep("Second",length(second_world_countries)),
rep("Third",length(third_world_countries)))
all_countries_categorised <- data.frame(country_name, categories)
nt_final_table_categorized <-merge(nt_final_table, all_countries_categorised, by ="country_name", all.x=TRUE)
nt_final_table_categorized
Sample output
country_name categories
1 Australia First
2 Austria First
3 Denmark First
4 Finland <NA>
5 Iceland First
6 Israel First
7 Luxembourg First
8 Netherlands First
9 New Zealand First
10 Norway First
11 Sweden First
12 Switzerland First

Get world region name from a country name in R

In my data I have one column with country names. I want to make a new variable that lists which region each country is in based on an excel sheet I have where I have labelled each country by region.
I don't want to use the package countrycode because it doesn't have specific enough regions (i.e. it labels the Netherlands as Europe, and not Northern Europe). Is there a way to get R to inspect a cell and match the contents of that cell to another dataset?
Import your spreadsheet into R. (Use RExcel, or export as CSV and import that using base functions.) Suppose your spreadsheet has two columns, named Country and Region, something like this:
regions <- data.frame(Country = c("Greece", "Netherlands"),
Region = c("Southern Europe", "Northern Europe"),
stringsAsFactors = FALSE)
regions
#> Country Region
#> 1 Greece Southern Europe
#> 2 Netherlands Northern Europe
Now create a named vector from the dataframe:
named <- regions$Region
names(named) <- regions$Country
named
#> Greece Netherlands
#> "Southern Europe" "Northern Europe"
Now you can index the named vector to convert country names to regions in any other vector.
other <- c("Netherlands", "Greece", "Greece")
named[other]
#> Netherlands Greece Greece
#> "Northern Europe" "Southern Europe" "Southern Europe"
If you have any missing countries (or variant spellings), you'll get NA for the region, e.g.
other2 <- c("Greece", "France")
named[other2]
#> Greece <NA>
#> "Southern Europe" NA
The rnaturalearth library has country shapefiles with region and subregion.
library(rnaturalearth)
world <- rnaturalearth::ne_countries(returnclass = "sf")
world$region
world$subregion

Get continent name from country name in R

I have a data frame with one column representing country names. My goal is to add one more column which gives the continent information. Please check the following use case:
my.df <- data.frame(country = c("Afghanistan","Algeria"))
Is there a package that I can use to append a column of data containing the continent names without having the original data?
You can use the countrycode package for this task.
library(countrycode)
df <- data.frame(country = c("Afghanistan",
"Algeria",
"USA",
"France",
"New Zealand",
"Fantasyland"))
df$continent <- countrycode(sourcevar = df[, "country"],
origin = "country.name",
destination = "continent")
#warning
#In countrycode(sourcevar = df[, "country"], origin = "country.name", :
# Some values were not matched unambiguously: Fantasyland
Result
df
# country continent
#1 Afghanistan Asia
#2 Algeria Africa
#3 USA Americas
#4 France Europe
#5 New Zealand Oceania
#6 Fantasyland <NA>
Expanding on Markus' answer, countrycode draws on codelists 'continent' declaration.
?codelist
Definition of continent:
continent: Continent as defined in the World Bank Development Indicators
The question asked for continents but sometimes continents don't provide enough groups for you to delineate the data. For example, continents groups North and South America into Americas.
What you might want is region:
region: Regions as defined in the World Bank Development Indicators
It is unclear how the World Bank groups regions but the below code shows how this destination is more granular.
library(countrycode)
egnations <- c("Afghanistan","Algeria","USA","France","New Zealand","Fantasyland")
countrycode(sourcevar = egnations, origin = "country.name",destination = "region")
Output:
[1] "Southern Asia"
[2] "Northern Africa"
[3] "Northern America"
[4] "Western Europe"
[5] "Australia and New Zealand"
[6] NA
You can try
my.df <- data.frame(country = c("Afghanistan","Algeria"),
continent= as.factor(c("Asia","Africa")))
merge(my.df, raster::ccodes()[,c("NAME", "CONTINENT")], by.x="country", by.y="NAME", all.x=T)
# country continent CONTINENT
# 1 Afghanistan Asia Asia
# 2 Algeria Africa Africa
Some country values might need an adjustment; I dunno since you did not provide all values.

R: changing values across multiple tables

I've been searching for a solution here and trying multiple methods to achieve what I want, but to no avail! I would really appreciate some help.
I have several tables with data on different countries. I need to merge these tables by country, but the same country is often referred to differently in each table, so I need to standardize them first.
Example table1:
birth_country mean_age
China 37
Germany 42
Example table2:
birth_country proportion_male
Federal Republic of Germany 54
China, People's Republic of 43
So I want to do something like this (which works when I do it as follows for a single table):
table1$birth_country[table1$birth_country == "China"] <- "China, People\'s Republic of"
table1$birth_country[table1$birth_country == "Federal Republic of Germany"] <- "Germany"
But no matter what I try, I can't seem to apply this sort of process to ALL of my tables. I've tried lapply and a for loop, in at least ten variations of the following...:
standardizeCountryNames<-function(x){
x[x == "China"] <- "China, People\'s Republic of"
x[x == "Federal Republic of Germany"] <- "Germany"
}
tables<-list(table1, table2, table3)
lapply(tables, function(i) {standardizeCountryNames(i$birth_country)})
and
for (k in 1:length(tables)){
tables[[k]]$birth_country[tables[[k]]$birth_country == "China"] <- "China, People\'s Republic of" }
I've tried referring to the birth_country variable in different ways, such as using with(table) and attach(table).
Any help would be greatly appreciated! (:
You were almost there:
table1 <- read.table(
text = "birth_country mean_age
China 37
Germany 42",
header = TRUE, stringsAsFactors = FALSE)
table2 <- read.table(
text = 'birth_country proportion_male
"Federal Republic of Germany" 54
"China, People\'s Republic of" 43',
header = TRUE, stringsAsFactors = FALSE)
standardizeCountryNames<-function(x){
x$birth_country[x$birth_country == "China"] <- "China, People\'s Republic of"
x$birth_country[x$birth_country == "Federal Republic of Germany"] <- "Germany"
x
}
tables<-list(table1, table2)
lapply(tables, function(i) {standardizeCountryNames(i)})
# [[1]]
# birth_country mean_age
# 1 China, People's Republic of 37
# 2 Germany 42
#
# [[2]]
# birth_country proportion_male
# 1 Germany 54
# 2 China, People's Republic of 43

Searching for multiple text patterns in R

This question is related to: Searching a data.frame in R
I want to search for multiple patterns , e.g. 'america' and 'united', in
all fields
in a given field
How can this be done? The case needs to be ignored.
Data:
ddf
id country area
1 1 United States of America North America
2 2 United Kingdom Europe
3 3 United Arab Emirates Arab
4 4 Saudi Arabia Arab
5 5 Brazil South America
ddf = structure(list(id = 1:5, country = c("United States of America",
"United Kingdom", "United Arab Emirates", "Saudi Arabia", "Brazil"
), area = c("North America", "Europe", "Arab", "Arab", "South America"
)), .Names = c("id", "country", "area"), class = "data.frame", row.names = c(NA,
-5L))
EDIT: To clarify, I have to search with AND and not OR. In this example, only 'United States of America' (row number 1) should come. If I search for 'brazil' and 'america', row number 5 should come (i.e. different search strings can be in different columns).
This actually fails for the "brazil" & "america" case but it was a useful test-bed for diagnosisng the logical problems;
hasAm <- sapply( ddf, grepl, patt="america", ignore.case=TRUE)
ddf[ rowSums(hasAm) > 0 , ]
#----------
id country area
1 1 United States of America North America
5 5 Brazil South America
#---------
hasUn <- sapply( ddf, grepl, patt="united", ignore.case=TRUE)
#---------
ddf[ rowSums( hasAm & hasUn) > 0 , ]
#-----------
id country area
1 1 United States of America North America
This edited version generalizes that strategy although it requires entering the selection criteria as a formula. I needed to first collapse each matrix so that summing across the cbind()-ed values didn't pick up multiple hits on a single term. So I have two rowSums, the outer one being done on m-column matrices where m is the number of terms in the formula, and the inner one being done on n-column matrices where n is the number of columns in the data-argument:
dfsel <- function(form, data) {
vars = all.vars(form)
selmatx <- lapply( vars, function(v)
sapply (data, grepl, patt=v, ignore.case=TRUE))
data[ rowSums( do.call(cbind,
lapply(selmatx,
function(L) {rowSums(L) > 0}) ) ) == length(vars)
, ] }
Demonstration:
> res <- dfsel( ~ united + america , ddf)
> res
id country area
1 1 United States of America North America
> res <- dfsel( ~ brazil + america , ddf)
> res
id country area
5 5 Brazil South America
Dumb way of solving it. Interested in other answers.
pattern<-c('America','United')
ddf1<-NULL
for (i in 1:length(pattern)){
new<-ddf[grep(paste0(pattern[i]),ddf$country),]
ddf1<-rbind(ddf1,new)
}
Going on the logic that no country in the world has "America" before "United" in its name, you could do
> f <- lapply(ddf, grep, pattern = "(united)(.*)(america)", ignore.case = TRUE)
> ddf[unique(unlist(f)), ]
# id country area
# 1 1 United States of America North America

Resources