-
Notifications
You must be signed in to change notification settings - Fork 2
Basic Mapping
WHAT ARE SHAPEFILES?
Shapefiles are spatial files with attribute information and they can be points, lines, or polygons. For instance, if you have a United States polygon shapefile, each state will have information (i.e. name, abbreviation, FIPS code, etc.) within the attribute table.
IMPORT SHAPEFILE
Use rgdal package and the readOGR function to import a shapefile into R. The readOGR function will read the projection file. new object name<- readOGR(dsn = "folder location with .shp extension", layer ="name only")
Users can also utilize the maptools package and the readShapePoly function. The readShapePoly function will NOT read the projection file and you will need to set the projection. new object name <- readShapePoly("folder location with .shp extension")
VIEW MAP
Use plot() function to view the map. The plot() function will display the shapefile with no background. If a background map is needed, use ggmap or leaflet. **Code for readOGR and plot are found in the "Shapefiles.R" script.
If you want to put shapefiles over imagery quickly, use ggmap and RgoogleMaps packages. First geocode the center of the map using geocode() function. Then use get_map() function. **Code is found in the "csv.R" script.
CLIP TWO SHAPEFILE LAYERS
First import both shapefile layers and view the extents of both layers using bbox() function. If needed, use the spTransform() function to project one layer to the other layer. Create a new object and set the newly projected layer to the polygon. In order to export the new spatial data frame to a shapefile, use the writeOGR() function. **Code is in the "Clip.R" script and you will get a result like this:
MERGE TWO SHAPEFILE LAYERS TOGETHER
You will need the rgdal, raster, rgeos libraries. First import both shapefiles using the readOGR() function. Finally, use the union function (for example: union(shp1, shp2)) and plot the result. **Code is available in the "Merge.R" script.
JOIN SHAPEFILE AND CSV ATTRIBUTES
You will need the sp library. First import the shapefile and csv files using readOGR() function and read.csv() function respectively. Note the names of the fields/columns that you will need to merge the two datasets together. Name a new object and use the merge() function. The csv fields will essentially be appended to the end of the shapefile fields/columns. **Code is available in the "AttributeJoin.R" script.
SPATIAL JOIN ON POINT AND POLYGON LAYERS
Import the rgdal library and both shapefiles. Use the over() function to return the rows for the column you specify. Then join back the new data created from the over() function by creating a new variable with a new column that you create. **See "Spatial_Join.R" script to view an example.
By: Jena Happ