Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
438 views
in Technique[技术] by (71.8m points)

maps - Get country (and continent) from longitude and latitude point in R

As a follow up on a question I posted yesterday, is there package/function within R that can give me the country (and continent) in which a point defined by longitude and latitude is located? Something along the lines of what is done here in MatLab.

Dataframe looks like this...

Point_Name              Longitude   Latitude
University of Arkansas  36.067832   -94.173655
Lehigh University       40.601458   -75.360063
Harvard University      42.379393   -71.115897

And I would like to output the above dataframe with country and continent columns added to it. As an added bonus, a column with US states for those in the US (and "other" for those outside the US)?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

To get continents you can modify the last line of the coords2country function using rworldmap from this answer to create a coords2continent function as shown below. Choose whether you want the 6 or 7 continent model. I'll think about putting this code into rworldmap.

library(sp)
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
coords2continent = function(points)
{  
  countriesSP <- getMap(resolution='low')
  #countriesSP <- getMap(resolution='high') #you could use high res map from rworldxtra if you were concerned about detail

  # converting points to a SpatialPoints object
  # 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)

  #indices$continent   # returns the continent (6 continent model)
  indices$REGION   # returns the continent (7 continent model)
  #indices$ADMIN  #returns country name
  #indices$ISO3 # returns the ISO3 code 
}

Here is a test.

points = data.frame(lon=c(0, 90, -45, -100, 130), lat=c(52, 40, -10, 45, -30 ))

coords2continent(points)
#[1] Europe        Asia          South America North America Australia  
coords2country(points)
#[1] United Kingdom  China   Brazil   United States of America  Australia

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...