Skip to content

Instantly share code, notes, and snippets.

@jeromyanglim
Created September 1, 2022 00:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jeromyanglim/8f549496aaf693eeb88d00171df32672 to your computer and use it in GitHub Desktop.
Save jeromyanglim/8f549496aaf693eeb88d00171df32672 to your computer and use it in GitHub Desktop.
Script for converting latitude and longitude coordinates (e.g., from Qualtrics) into country codes using R
# Script for converting latitude and longitude coordinates (e.g., from Qualtrics) into country codes using R
# Assumes data set is called rcases
# country from coords
library(sp)
# install.packages("rworldmap")
library(rworldmap)
# The single argument to this function, points, is a data.frame in which:
# - column 1 contains the longitude in degrees
# - column 2 contains the latitude in degrees
coords2country = function(points)
{
# https://stackoverflow.com/a/14342127/180892
countriesSP <- getMap(resolution='low')
#countriesSP <- getMap(resolution='high') #you could use high res map from rworldxtra if you were concerned about detail
# convert our list of points to a SpatialPoints object
# pointsSP = SpatialPoints(points, proj4string=CRS(" +proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs +towgs84=0,0,0"))
#setting CRS directly to that from rworldmap
pointsSP = SpatialPoints(points, proj4string=CRS(proj4string(countriesSP)))
# use 'over' to get indices of the Polygons object containing each point
indices = over(pointsSP, countriesSP)
# return the ADMIN names of each country
indices$ADMIN
#indices$ISO3 # returns the ISO3 code
#indices$continent # returns the continent (6 continent model)
#indices$REGION # returns the continent (7 continent model)
}
rcases$locationlatitude <- as.numeric(rcases$locationlatitude)
rcases$locationlongitude <- as.numeric(rcases$locationlongitude)
rcases$ipcountry <- coords2country(rcases[, c("locationlongitude", "locationlatitude" )])
rcases$ipcountry <- as.character(rcases$ipcountry)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment