6 R as a GIS

6.1 Overview

Points, lines, polygons and rasters - R can handle them all and more! R is a free software environment for statistical computing and graphics, but its abilities have been extended into many realms through the >20,000 (!) contributed extension packages (also called libraries).

The list of packages can be bewildering, but fortunately some great folks have taken the time to sift through and make some sense of them for different focal topics and created Task Views.

For GIS there are two Task Views of interest:

  • Spatial - maintained by Roger Bivand and Jakub Nowosad, and
  • SpatioTemporal - maintained by Edzer Pebesma and Roger Bivand

They overlap somewhat, but the latter specifically focuses on data where both location and time of observation are registered, and relevant for the analysis of the data.

Each has an overview page listing packages and highlighting their respective strengths, weaknesses etc., e.g.

Screenshot of the "Spatial" Task View at [https://cran.r-project.org/](https://cran.r-project.org/)

Figure 6.1: Screenshot of the “Spatial” Task View at https://cran.r-project.org/

The Spatial Task View focuses on “Analysis of Spatial Data”, with sections on:

  • Classes for spatial data and metadata
  • Reading and writing spatial data
  • Handling spatial data
  • Visualizing spatial data
  • Analyzing spatial data

Task Views also allow easy download and installation of all packages in a Task View using library(ctv) (which you can install with install.packages("ctv")). In this case the code you’d need to install the Task View is ctv::install.views("Spatial", coreOnly = TRUE). But beware! If you leave out the coreOnly = TRUE it can take a while to download and install!!! It may take a while even then… You don’t need the whole Task View for my tutorials, so don’t bother downloading it if you’re just working through these.

Screenshot of the Task View landing page at [https://cran.r-project.org/](https://cran.r-project.org/)

Figure 6.2: Screenshot of the Task View landing page at https://cran.r-project.org/

6.2 Some key R packages

We don’t have time to go through all packages or provide a full history, but here are some notes in brief.

6.2.1 For vector data

(although some of these packages can handle rasters too)

The leading package was sp. It is still active and useful, but is superseded by a newer package sf, which is a modern implementation and standardization of parts of sp. It is highly recommended that you use sf over the older packages as they will not be maintained in the long term, largely because they rely on other packages that are no longer maintained because their creators have retired.

sf stands for “Simple Features for R”, in compliance with the OGC Simple Feature standard. It is highly efficient, and comes with the advantage that it uses Tidyverse principles and coding styles, e.g. allowing use of the pipe operator (%>%) and the direct application of library(dplyr) data manipulation and library(ggplot2) visualization functions.

I will use sf for the most part in the demonstration material. Unfortunately, not all operations are available in sf yet and I may still have to use sp at times, especially when performing operations using both vector and raster data.

Here’s a quick list of the functions available in sf:

methods(class = 'sf')
##   [1] [                            [[<-                         [<-                         
##   [4] $<-                          aggregate                    anti_join                   
##   [7] arrange                      as.data.frame                cbind                       
##  [10] coerce                       crs                          dbDataType                  
##  [13] dbWriteTable                 df_spatial                   distance                    
##  [16] distinct                     dplyr_reconstruct            drop_na                     
##  [19] duplicated                   ext                          extent                      
##  [22] extract                      filter                       full_join                   
##  [25] gather                       group_by                     group_split                 
##  [28] identify                     initialize                   inner_join                  
##  [31] left_join                    lines                        mapView                     
##  [34] mask                         merge                        mutate                      
##  [37] nest                         pivot_longer                 pivot_wider                 
##  [40] plot                         points                       polys                       
##  [43] print                        raster                       rasterize                   
##  [46] rbind                        rename_with                  rename                      
##  [49] right_join                   rowwise                      sample_frac                 
##  [52] sample_n                     select                       semi_join                   
##  [55] separate_rows                separate                     show                        
##  [58] slice                        slotsFromS3                  spread                      
##  [61] st_agr                       st_agr<-                     st_area                     
##  [64] st_as_s2                     st_as_sf                     st_as_sfc                   
##  [67] st_bbox                      st_boundary                  st_break_antimeridian       
##  [70] st_buffer                    st_cast                      st_centroid                 
##  [73] st_collection_extract        st_concave_hull              st_convex_hull              
##  [76] st_coordinates               st_crop                      st_crs                      
##  [79] st_crs<-                     st_difference                st_drop_geometry            
##  [82] st_filter                    st_geometry                  st_geometry<-               
##  [85] st_inscribed_circle          st_interpolate_aw            st_intersection             
##  [88] st_intersects                st_is_valid                  st_is                       
##  [91] st_join                      st_line_merge                st_m_range                  
##  [94] st_make_valid                st_minimum_rotated_rectangle st_nearest_points           
##  [97] st_node                      st_normalize                 st_point_on_surface         
## [100] st_polygonize                st_precision                 st_reverse                  
## [103] st_sample                    st_segmentize                st_set_precision            
## [106] st_shift_longitude           st_simplify                  st_snap                     
## [109] st_sym_difference            st_transform                 st_triangulate_constrained  
## [112] st_triangulate               st_union                     st_voronoi                  
## [115] st_wrap_dateline             st_write                     st_z_range                  
## [118] st_zm                        summarise                    svc                         
## [121] transform                    transmute                    ungroup                     
## [124] unite                        unnest                       vect                        
## see '?methods' for accessing help and source code

This doesn’t tell you how to use them though. To get help with a function in R just type “?” followed by the function name, e.g. ?st_read, and it’ll take you to the help page.

Of course, you don’t want to have to read every help page to find the function you want! Fortunately, here’s a “cheat sheet” that allows you to find the function you want relatively quickly (once you’re familiar with the syntax etc):

An R [_cheat sheet_ for library(sf)](https://github.com/rstudio/cheatsheets/blob/main/sf.pdf) by Ryan Garnett (page 1).

Figure 6.3: An R cheat sheet for library(sf) by Ryan Garnett (page 1).

An R [_cheat sheet_ for library(sf)](https://github.com/rstudio/cheatsheets/blob/main/sf.pdf) by Ryan Garnett (page 2).

Figure 6.4: An R cheat sheet for library(sf) by Ryan Garnett (page 2).

6.2.2 For raster data

By far the best package has been raster, maintained by Robert Hijmans (of WorldClim fame), and can do just about anything with rasters and interfaces with sp very nicely. Unfortunately, both raster and sp are being phased out as explained above. raster is currently being superseded by a new package called terra, also being developed by Hijmans.

“terra is very similar to the raster package; but terra is simpler, better, and faster” - Roger Bivand

I first developed this module using raster, because terra was still largely in development, so I have kept the demonstrations of raster for those who depend on them for now, but highly recommend you start using terra, because I’ll likely remove the raster material next year. It’s worth noting that raster and terra can handle vector data directly too, and that sometimes their integration with sf is a little clunky, but it does seem to get better all the time. Unfortunately, there’s no cheat sheet for terra or raster, but there’s a lot of documentation and tutorials here.

terra is also able to handle spatiotemporal arrays (raster and vector data cubes). Think of these as time-series of GIS data, like satellite archives, etc. Other powerful packages to watch in the spatiotemporal space are stars and gdalcubes.