⚠️There's a newer version (1.0.4) of this package. Take me there.

RQGIS

RQGIS establishes an interface between R and QGIS, i.e. it allows the user to access QGIS functionalities from within R. It achieves this by using the QGIS API via the command line. This provides the user with an extensive suite of GIS functions, since QGIS allows you to call native as well as third-party algorithms via its processing framwork (see also https://docs.qgis.org/2.14/en/docs/user_manual/processing/index.html). Third-party providers include among others GDAL, GRASS GIS, SAGA GIS, the Orfeo Toolbox, TauDEM and tools for LiDAR data. RQGIS brings you this incredibly powerful geoprocessing environment to the R console.

<img src="figures/r_qgis_puzzle.png", width="40%" height="40%" style="display: block; margin: auto;" />

The main advantages of RQGIS are:

  1. It provides access to QGIS functionalities. Thereby, it calls Python from the command line (QGIS API) but R users can stay in their programming environment of choice without having to touch Python.
  2. It offers a broad suite of geoalgorithms making it possible to solve virtually any GIS problem.
  3. R users can just use one package (RQGIS) instead of using RSAGA and spgrass to access SAGA and GRASS functions. This, however, does not mean that RSAGA and spgrass are obsolete since both packages offer various other advantages. For instance, RSAGA provides many user-friendly and ready-to-use GIS functions such as rsaga.slope.asp.curv and multi.focal.function.

Installation

Package installation

In order to run RQGIS properly, you need to download various third-party software packages. Our vignette should help you with the download and installation procedures on various platforms (Windows, Linux, Mac OSX). To access it, use vignette("install_guide", package = "RQGIS"). Overall, we recommend to use the current LTR of QGIS (2.14) with RQGIS.

You can install the latest RQGIS development version from Github with:

if (packageVersion("devtools") < 1.6) {
    install.packages("devtools")    
    }
if (!"lazyeval" %in% installed.packages()[, "Package"]) {
devtools::install_github("hadley/lazyeval")  
}
devtools::install_github("jannes-m/RQGIS", build_vignettes = TRUE)

Before running these lines under Linux (Ubuntu), you need to install some devtools dependencies via the terminal:

sudo apt-get install libssl-dev
# add curl repository to sources.list
sudo sh -c 'echo "deb http://security.ubuntu.com/ubuntu precise-security main" >> /etc/apt/sources.list'
sudo apt-get update
# finally you can install libcurl
sudo apt-get install libcurl4-gnutls-dev

QGIS 2.16 modifications

If you only installed the most recent QGIS version (2.16.1), you need to fix manually a Processing error in order to make RQGIS work. First, add one import statement (SilentProgress) to ../processing/gui/AlgorithmExecutor.py. Secondly replace python alg.execute(progress) by python alg.execute(progress or SilentProgress()):

<img src="figures/rewrite_algexecutor.PNG", width="80%" height="80%" style="display: block; margin: auto;" />

The QGIS core team has already fixed this issue (see also this post). Hence, with the next minor release the manual adjustment is hopefully no longer required.

For Windows users: If you installed both the LTR and the most recent QGIS version, you don't need to adjust anything since RQGIS will use by default the LTR (2.14).

RQGIS usage

Subsequently, we will show you a typical workflow of how to use RQGIS. Basically, we will follow the steps also described in the QGIS documentation. In our first and very simple example we simply would like to retrieve the centroid coordinates of a spatial polygon object. First off, we will download the administrative areas of Germany using the raster package.

# attach packages
library("raster")
library("rgdal")

# define path to a temporary folder
dir_tmp <- tempdir()
# download German administrative areas 
ger <- getData(name = "GADM", country = "DEU", level = 1)
# ger is of class "SpatialPolygonsDataFrame"

Now that we have a spatial object, we can move on to using RQGIS. First of all, we need to specify all the paths necessary to run the QGIS-API. Fortunately, set_env does this for us (assuming that QGIS and all necessary dependencies were installed correctly). The only thing we need to do is: specify the root path to the QGIS-installation. If you do not specify a path, set_env tries to find the OSGeo4W-installation on your C: drive (Windows) though this might take a while. If you are running RQGIS under Linux or on a Mac, set_env assumes that your root path is "/usr" and "/applications/QGIS.app/Contents", respectively. Please note, that most of the RQGIS functions, you are likely to work with (such as find_algorithms, get_args_man and run_qgis), require the output list (as returned by set_env) containing the paths to the various installations necessary to run QGIS from within R.

# attach RQGIS
library("RQGIS")

# set the environment, i.e. specify all the paths necessary to run QGIS from 
# within R
my_env <- set_env()
#> Trying to find OSGeo4W on your C: drive.
# under Windows set_env would be much faster if you specify the root path:
# my_env <- set_env("C:/OSGeo4W~1")
# have a look at the paths necessary to run QGIS from within R
my_env
#> $root
#> [1] "C:\\OSGeo4W64"
#> 
#> $qgis_prefix_path
#> [1] "C:\\OSGeo4W64\\apps\\qgis-ltr"
#> 
#> $python_plugins
#> [1] "C:\\OSGeo4W64\\apps\\qgis-ltr\\python\\plugins"

Secondly, we would like to find out how the function in QGIS is called which gives us the centroids of a polygon shapefile. To do so, we use find_algorithms. We suspect that the function we are looking for contains the words polygon and centroid.

# look for a function that contains the words "polygon" and "centroid"
find_algorithms(search_term = "polygon centroid", 
                qgis_env = my_env)
#> [1] "Polygon centroids------------------------------------>qgis:polygoncentroids"
#> [2] "Polygon centroids------------------------------------>saga:polygoncentroids"
#> [3] ""

This gives us two functions we could use. Here, we'll choose the QGIS function named qgis:polygoncentroids. Subsequently, we would like to know how we can use it, i.e. which function parameters we need to specify.

get_usage(alg = "qgis:polygoncentroids",
          qgis_env = my_env,
          intern = TRUE)
#> [1] "ALGORITHM: Polygon centroids"   "\tINPUT_LAYER <ParameterVector>"
#> [3] "\tOUTPUT_LAYER <OutputVector>"   ""                              
#> [5] ""                               ""

Consequently qgis:polygoncentroids only expects a parameter called INPUT_LAYER, i.e. the path to a polygon shapefile whose centroid coordinates we wish to extract, and a parameter called OUTPUT_LAYER, i.e. the path to the output shapefile. Since it would be tedious to specify manually each and every function argument, especially if a function has more than two or three arguments, we have written a convenience function named get_args_man. This function basically mimics the behavior of the QGIS GUI, i.e. it retrieves all function arguments and respective default values for a given GIS function. It returns these values in the form of a list, i.e. exactly in the format as expected by run_qgis (see further below). If a function argument lets you choose between several options (drop-down menu in a GUI), setting get_arg_man's options-argument to TRUE makes sure that the first option will be selected (QGIS GUI behavior). For example, qgis:addfieldtoattributestable has three options for the FIELD_TYPE-parameter, namely integer, float and string. Setting options to TRUE means that the field type of your new column will be of type integer.

params <- get_args_man(alg = "qgis:polygoncentroids", 
                       qgis_env = my_env)
params
#> $INPUT_LAYER
#> [1] "None"
#> 
#> $OUTPUT_LAYER
#> [1] "None"

In our case, qgis:polygoncentroids has only two function arguments and no default values. Naturally, we need to specify manually our input and output layer. Tab-completion, as for instance provided by the wonderful RStudio IDE, greatly fascilitates this task. Please note that instead of specifying a path to INPUT_LAYER (e.g. "ger.shp") you can also use a spatial object that resides in the global environment of R. Conveniently, run_qgis will save this spatial object to a temporary location for you later on (see below). Here, we use the SpatialPolygonsDataFrame ger as input layer.

# specify input layer
params$INPUT_LAYER  <- ger
# path to the output shapefile
params$OUTPUT_LAYER <- file.path(dir_tmp, "ger_coords.shp")

Finally, run_qgis calls the QGIS API to run the specified geoalgorithm with the corresponding function arguments. Aside from accepting spatial objects living in R as input, run_qgis also loads the result directly into R, if desired. Here, we would like to load the OUTPUT_LAYER into R. To do so, we simply specify the desired file(s) in function argument load_output while assigning it/them to an object called out.

out <- run_qgis(alg = "qgis:polygoncentroids",
                params = params,
                load_output = params$OUTPUT_LAYER,
                qgis_env = my_env)

Excellent! No error message occured, that means QGIS created a points shapefile containing the centroids of our polygons shapefile. Naturally, we would like to check if the result meets our expectations.

# first, plot the federal states of Germany
plot(ger)
# next plot the centroids created by QGIS
plot(out, pch = 21, add = TRUE, bg = "lightblue", col = "black")

Of course, this is a very simple example. We could have achieved the same using sp::coordinates. To harness the real power of integrating R with a GIS, we will present a second, more complex example. Yet to come in the form of a paper...

TO DO:

  • check package and upload it to CRAN!!!
  • build_cmds: py_cmd could be a one liner for all platforms
  • Take care of the error message: ERROR 1: Can't load requested DLL: C:4~1_FileGDB.dll 193: %1 ist keine zulässige Win32-Anwendung.
  • open_help: automatically construct a helpfile if no documentation is availabe on the Internet (-> if Python web scraping "Error" is True, construct html file)
  • does it make sense to create a RQGIS-class?
  • qgis_session_info -> add OTB and Lidar to the list

Copy Link

Version

Down Chevron

Monthly Downloads

59

Version

0.1.0

License

GPL-2

Issues

Pull Requests

Stars

Forks

Maintainer

Last Published

August 15th, 2016

Functions in RQGIS (0.1.0)