Skip to contents

Converts country names to their corresponding ISO3 codes. The function uses a hierarchical matching strategy: first trying exact match, then prefix and partial matches if the input is long enough, while avoiding matches on common words.

Usage

wp_ctry2iso(country_name, verbose = TRUE, min_letter = 5)

Arguments

country_name

Character vector containing the country names to convert. The function accepts various formats and spellings, including:

  • Official names (e.g., "United States of America")

  • Common names (e.g., "United States", "USA")

  • Historical names (e.g., "Burma" for Myanmar)

  • Names with special characters (e.g., "Côte d'Ivoire")

  • Names with abbreviations (e.g., "Rep." for Republic)

verbose

Logical, whether to print information about matching method used when exact match fails (default: TRUE)

min_letter

Integer, minimum number of letters required for prefix and partial matching attempts (default: 5). Only used if exact match fails.

Value

Character vector of the same length as country_name containing ISO3 codes. Returns NA for entries where no match is found, with a warning message if verbose=TRUE.

Details

The function performs matching in the following order:

  1. Normalizes input name (converts to lowercase, removes special characters, standardizes spacing)

  2. Attempts exact match with normalized names

  3. If exact match fails and input length >= min_letter:

    • Tries prefix match (input matches start of country name)

    • Tries partial match (input is contained within country name)

    • Skips matching on common words like "United", "Republic", etc.

    • If verbose=TRUE, informs user about successful prefix/partial match

See also

wp_from_iso for converting ISO codes back to country names, wp_get_category for getting countries in specific categories

Other country code conversion functions: wp_from_iso()

Examples

# Single country
wp_ctry2iso("France")  # Returns "FRA"
#> France 
#>  "FRA" 

# Multiple countries
wp_ctry2iso(c("India", "China", "Italy"))  # Returns c("IND", "CHN", "ITA")
#> India China Italy 
#> "IND" "CHN" "ITA" 

# Mixed cases with some partial matches, short abbreviations, and errors
wp_ctry2iso(c("franc", "Deutsche", "Kingdom", "us", "UAE", "Jamai")) 
#>  [PREFIX] Found prefix match: input 'franc' matched with country 'France' 
#> /!\  ISO code for country name 'Deutsche' (deutsche) not found. NA value returned. 
#> /!\  ISO code for country name 'Kingdom' (kingdom) not found. NA value returned. 
#>  [PREFIX] Found prefix match: input 'Jamai' matched with country 'Jamaica' 
#>    franc Deutsche  Kingdom       us      UAE    Jamai 
#>    "FRA"       NA       NA    "USA"    "ARE"    "JAM"