28.4. Appendix D: QGIS R script syntax

Contributed by Matteo Ghetta - funded by Scuola Superiore Sant’Anna

Writing R scripts in Processing is a bit tricky because of the special syntax.

A Processing R script starts with defining its Inputs and Outputs, each preceded with double hash characters (##).

Before the inputs, the group to place the algoritm in can be specified. If the group already exists, the algorithm will be added to it, if not, the group will be created. In the example below, the name of the group is My group:

##My Group=group

28.4.1. Eingaben

All input data and parameters have to be specified. There are several types of inputs:

  • vector: ##Layer = vector

  • vector field: ##F = Field Layer (where Layer is the name of an input vector layer the field belongs to)

  • raster: ##r = raster

  • table: ##t = table

  • number: ##Num = number

  • string: ##Str = string

  • boolean: ##Bol = boolean

  • elements in a dropdown menu. The items must be separated with semicolons ;: ##type=selection point;lines;point+lines

28.4.2. Ausgaben

Genau wie die Eingaben müssen alle Ausgaben am Beginn des Skriptes definiert werden:

  • vector: ##output= output vector

  • raster: ##output= output raster

  • table: ##output= output table

  • plots: ##output_plots_to_html (##showplots in earlier versions)

  • To show R output in the Result Viewer, put > in front of the command whose output you would like to show.

28.4.3. Syntax Summary for QGIS R scripts

A number of input and output parameter types are offered.

28.4.3.1. Input parameter types

Parameter

Syntax Beispiel

Rückgabeobjekte

vector

Layer = vector

sf object (or SpatialDataFrame object, if ##load_vector_using_rgdal is specified)

vector point

Layer = vector point

sf object (or SpatialDataFrame object, if ##load_vector_using_rgdal is specified)

vector line

Layer = vector line

sf object (or SpatialDataFrame object, if ##load_vector_using_rgdal is specified)

vector polygon

Layer = vector polygon

sf object (or SpatialPolygonsDataFrame object, if ##load_vector_using_rgdal is used)

multiple vector

Layer = multiple vector

sf object (or SpatialDataFrame objects if ##load_vector_using_rgdal is specified)

table

Layer = table

Datenrahmenumwandlung von csv, voreingestelltes Objekt der read.csv Funktion

field

Field = Field Layer

Name des ausgewählten Feldes, z.B. "Area"

raster

Layer = raster

RasterBrick Objekt, voreingestelltes Objekt des raster Pakets

multiple raster

Layer = multiple raster

RasterBrick Objekt, voreingestelltes Objekt des raster Pakets

number

N = number

gewählte Ganzzahl oder Fließkommazahl

string

S = string

in der Box eingefügte Zeichenkette

longstring

LS = longstring

in der Box eingefügte Zeichenkette, kann länger als eine normale Zeichenkette sein

selection

S = selection first;second;third

Zeichenkette des im dropdown-Menü gewählten Objektes

crs

C = crs

Zeichenkette des sich ergebenen KBS im Format: "EPSG:4326"

extent

E = extent

Ausdehnungsobjekt des raster Pakets, man kann Werte als E@xmin` extrahieren

point

P = point

beim Klicken auf die Karte erhält man die Koordinaten des Punktes

file

F = file

Pfad der gewählten Datei, z.B. „/home/matteo/file.txt“

folder

F = folder

Pfad des gewählten Ordners, z.B „/home/matteo/Downloads“

A parameter can be OPTIONAL, meaning that it can be ignored.

In order to set an input as optional, you add the string optional before the input, e.g:

##Layer = vector
##Field1 = Field Layer
##Field2 = optional Field Layer

28.4.3.2. Output parameter types

Parameter

Syntax Beispiel

vector

Output = output vector

raster

Output = output raster

table

Output = output table

file

Output = output file

Bemerkung

You can save plots as png from the Processing Result Viewer, or you can choose to save the plot directly from the algorithm interface.

28.4.3.3. Skript Hauptteil

The script body follows R syntax and the Log panel can help you if there is something wrong with your script.

Remember that you have to load all additional libraries in the script:

library(sp)

28.4.4. Beispiele

28.4.4.1. Beispiel mit Vektorausgabe

Sehen wir uns einen Algorithmus aus der Onlinesammlung an, der zufällige Punkte innerhalb der Ausdehnung eines Eingabelayers erstellt:

##Point pattern analysis=group
##Layer=vector polygon
##Size=number 10
##Output=output vector
library(sp)
spatpoly = as(Layer, "Spatial")
pts=spsample(spatpoly,Size,type="random")
spdf=SpatialPointsDataFrame(pts, as.data.frame(pts))
Output=st_as_sf(spdf)

Explanation (per line in the script):

  1. Point pattern analysis ist die Gruppe des Algorithmus

  2. Layer ist der Eingabevektorlayer

  3. Size is a numerical parameter with a default value of 10

  4. Output ist der Vektorlayer der vom Algorithmus erstellt wird

  5. library(sp) loads the sp library

  6. spatpoly = as(Layer, "Spatial") translate to an sp object

  7. Call the spsample function of the sp library and run it using the input defined above (Layer and Size)

  8. Create a SpatialPointsDataFrame object using the SpatialPointsDataFrame function

  9. Create the output vector layer using the st_as_sf function

That’s it! Just run the algorithm with a vector layer you have in the QGIS Legend, choose the number of random point. The resulting layer will be added to your map.

28.4.4.2. Beispiel mit Rasterausgabe

The following script will perform basic ordinary kriging to create a raster map of interpolated values from a specified field of the input point vector layer by using the autoKrige function of the automap R package. It will first calculate the kriging model and then create a raster. The raster is created with the raster function of the raster R package:

##Basic statistics=group
##Layer=vector point
##Field=Field Layer
##Output=output raster
##load_vector_using_rgdal
require("automap")
require("sp")
require("raster")
table=as.data.frame(Layer)
coordinates(table)= ~coords.x1+coords.x2
c = Layer[[Field]]
kriging_result = autoKrige(c~1, table)
prediction = raster(kriging_result$krige_output)
Output<-prediction

By using ##load_vector_using_rgdal, the input vector layer will be made available as a SpatialDataFrame objects, so we avoid having to translate it from an sf object.

28.4.4.3. Beispiel mit Tabellenausgabe

Lassen Sie uns den Algorithmus Summary Statistics bearbeiten, so dass als Ausgabe eine Tabelle (csv) erzeugt wird.

Der Hauptteil des Skriptes sieht wie folgt aus:

##Basic statistics=group
##Layer=vector
##Field=Field Layer
##Stat=Output table
Summary_statistics<-data.frame(rbind(
    sum(Layer[[Field]]),
    length(Layer[[Field]]),
    length(unique(Layer[[Field]])),
    min(Layer[[Field]]),
    max(Layer[[Field]]),
    max(Layer[[Field]])-min(Layer[[Field]]),
    mean(Layer[[Field]]),
    median(Layer[[Field]]),
    sd(Layer[[Field]])),
  row.names=c("Sum:","Count:","Unique values:","Minimum value:","Maximum value:","Range:","Mean value:","Median value:","Standard deviation:"))
colnames(Summary_statistics)<-c(Field)
Stat<-Summary_statistics

Die dritte Zeile gibt als Eingabe Vector Field vor. In der vierten Zeile wird die Ausgabe des Algorithmus als Tabelle festgelegt.

In der letzten Zeile wird das im Skript erstellte Objekt Stat in eine csv Tabelle umgewandelt.

28.4.4.4. Beispiel mit Konsolenausgabe

We can use the previous example and instead of creating a table, print the result in the Result Viewer:

##Basic statistics=group
##Layer=vector
##Field=Field Layer
Summary_statistics<-data.frame(rbind(
sum(Layer[[Field]]),
length(Layer[[Field]]),
length(unique(Layer[[Field]])),
min(Layer[[Field]]),
max(Layer[[Field]]),
max(Layer[[Field]])-min(Layer[[Field]]),
mean(Layer[[Field]]),
median(Layer[[Field]]),
sd(Layer[[Field]])),row.names=c("Sum:","Count:","Unique values:","Minimum value:","Maximum value:","Range:","Mean value:","Median value:","Standard deviation:"))
colnames(Summary_statistics)<-c(Field)
>Summary_statistics

The script is exactly the same as the one above except for two edits:

  1. no output specified (the fourth line has been removed)

  2. the last line begins with >, telling Processing to make the object available through the result viewer

28.4.4.5. Beispiel mit Plot

To create plots, you have to use the ##output_plots_to_html parameter as in the following script:

##Basic statistics=group
##Layer=vector
##Field=Field Layer
##output_plots_to_html
####output_plots_to_html
qqnorm(Layer[[Field]])
qqline(Layer[[Field]])

The script uses a field (Field) of a vector layer (Layer) as input, and creates a QQ Plot (to test the normality of the distribution).

The plot is automatically added to the Processing Result Viewer.