rspatial / geodata

download geographic data
GNU General Public License v3.0
147 stars 15 forks source link

feature request: queries for country_codes #40

Closed plantarum closed 1 year ago

plantarum commented 1 year ago

I have a suggestion for the convenience function country_codes. It works fine as is, but it might be nice to allow users to query it directly for a particular country or region.

Here's my idea:

country_codes <- function(query = NULL) {
    path <- system.file(package="geodata")
    #d <- utils::read.csv(paste(path, "/ex/countries.csv", sep=""), stringsAsFactors=FALSE, encoding="UTF-8")
    res <- readRDS(file.path(path, "ex/countries.rds"))
        if(is.null(query)){
          res
        } else {
          hits <- apply(res, 1, function(x) any(grepl(query, x,
                                                      ignore.case = TRUE)))
          res[hits, ]
        }
}

The default behaviour is unchanged. But if I want to quickly look up a particular location, I can do:

> country_codes("mexico")
      NAME ISO3 ISO2 NAME_ISO NAME_FAO                      NAME_LOCAL
145 Mexico  MEX   MX   MEXICO   Mexico México|Estados Unidos Mexicanos
    SOVEREIGN       UNREGION1 UNREGION2     continent
145    México Central America  Americas North America

country_codes("mx")
      NAME ISO3 ISO2 NAME_ISO NAME_FAO                      NAME_LOCAL
145 Mexico  MEX   MX   MEXICO   Mexico México|Estados Unidos Mexicanos
    SOVEREIGN       UNREGION1 UNREGION2     continent
145    México Central America  Americas North America

> country_codes("samoa")
              NAME ISO3 ISO2       NAME_ISO       NAME_FAO     NAME_LOCAL
6   American Samoa  ASM   AS AMERICAN SAMOA American Samoa American Samoa
197          Samoa  WSM   WS          SAMOA          Samoa          Samoa
        SOVEREIGN UNREGION1 UNREGION2 continent
6   United States Polynesia   Oceania   Oceania
197         Samoa Polynesia   Oceania   Oceania

> country_codes("guinea")
                 NAME ISO3 ISO2          NAME_ISO          NAME_FAO
71  Equatorial Guinea  GNQ   GQ EQUATORIAL GUINEA Equatorial Guinea
96      Guinea-Bissau  GNB   GW     GUINEA-BISSAU     Guinea-Bissau
97             Guinea  GIN   GN            GUINEA            Guinea
175  Papua New Guinea  PNG   PG  PAPUA NEW GUINEA  Papua New Guinea
           NAME_LOCAL         SOVEREIGN      UNREGION1 UNREGION2 continent
71  Guinea Ecuatorial Equatorial Guinea  Middle Africa    Africa    Africa
96       Guiné-Bissau     Guinea-Bissau Western Africa    Africa    Africa
97             Guinee            Guinea Western Africa    Africa    Africa
175    Papua Niu Gini  Papua New Guinea      Melanesia   Oceania   Oceania

Not anything you can't do with an extra line or two of code, but maybe useful nevertheless?

Thanks for all your work, I'm really enjoying terra et al. as I update my scripts!

Best,

Tyler

rhijmans commented 1 year ago

Thanks, great idea. Implemented. Sorry for the long wait.