User Tools

Site Tools



GRASS via spgrass6

Things we cover

If you want to use the full power of GRASS GIS from R you have to use the spgrass6 package. It is a wrapper interface for the GRASS GIS system. The documentation tells that it is an “interpreted interface between GRASS geographical information system, versions 6 and 7, and R, based on starting R from within the GRASS environment, or on running R stand-alone and creating a throw-away GRASS environment from within R”.

Keep in mind that spgrass6 (as GRASS) only works with the GRASS internal file format (stored within location and mapset folder hierarchy). Mention all this files will be stored on your hard drive in the assigned folders. We will cover:

  • how to initialize spgrass6 in a very effective but quick and dirty way
  • some Linux and Windows specific stuff
  • straightforward utilization of the GRASS functionality

Things you need

  • The spgrass6 package provides a comfortable R to GRASS interface for the GRASS versions 6 and 7. It is a wrapper package what means that it works slightly different to “normal” R packages.

    Using GRASS GIS directly in R is two folded:

    • First you may run R outside of GRASS, transferring GRASS data and results to R do something with them and and re-import the R results back to GRASS.
    • Second you may use R as a scripting language basically using the execGRASS function.

    Note: you need a Running installation of GRASS GIS on your system.

    if (!require(spgrass6)){install.packages(spgrass6)}

Things to do

Install and setup of spgrass6

For the use of spgrass6 you need obviously a employable installation of GRASS on your system. You may use any installation because there should be no problem with version or pathes. Nevertheless it is a little tricky to handle GRASS correctly. This is because of the rigid GRASS policy how to deal with geodata in questions of storage and and projections.

The correct setup of spgrass6 might be troublesome for Windows Systems, especially if you use the GRASS version that is integrated in the QGIS distribution. Furthermore at the moment only Windows 7 is working stable. Please have a look at the FAQ list of known Windows issues .

The setup below try to make it as easy as possible. For the examples the Windows standalone GRASS 6.4.3. version was used. It is Integrated in the WinR-RIS2Go compilation.

In order to clarify it: GRASS demands a defined and projected so called location and mapset. The first is folder with a defined projection, the second is arbitrary spatial container (implemented as a sub folder), that uses this projection. Furthermore all GRASS locations have an default mapset called PERMANENT. There are two ways of dealing with GRASS - the common one is that you open GRASS and define a location and mapset to your needs before starting the GRASS GUI. The other way is that you deal permanently with the extends and projection data while you work with grass modules from external programs.

We will choose the happy medium of it. If you want to utilize quick and easy the GRASS benefit it is more flexible to create locations and mapsets during the execution of the script. Of course you should be carefully because we have to control the spatial settings.

# install spgrass6
if (!require(raster)){install.packages("raster")}
if (!require(spgrass6)){install.packages("spgrass6")}
# GRASS is forcing us to provide in the beginning a georeference system
# so beside the other well known arguments we additionally  provide 
# our current EPSG Code  location name and mapset name
# arguments for all GIS APIs<-"test.asc"                # input DEM (has to be GDAL conform)
epsg.code<-'EPSG:31254'           # EPSG Code for input ASC file
root.dir <- "/home/MOC/aGIS"      # root folder 
working.dir <- "wise2014"         # working folder 
# (spgrass6) define GRASS arguments
grass.epsg.code<- as.numeric(substring(epsg.code,6,10))  # take substring defined projection
grass.loc<- paste0('loc',substring(epsg.code,6,10))      # define corresponding folder name
grass.mapset<- 'PERMANENT'                               # NOTE "PERMANENT" is the GRASS default
                                                         # If you want to use another mapset 
                                                         # define it here
# To define a temporary and/or permanent  GRASS environment is a bit tricky. 
# This is because of fact that GRASS forces very strictly a defined location and mapset. 
# Usually you initialize it interactively while starting or working with standalone GRASS.
# We use a "happy middle dirty workaround"
# (1) if not exist create (flags='c') a new grass location with the needed projection
if (!file.exists(file.path(root.dir, working.dir,grass.loc))){
    execGRASS('g.proj', flags=c('t','c') ,  epsg=grass.epsg.code, location=grass.loc)
# (2) now initialize GRASS Note "PERMANENT" is the ALWAYS existing default mapset 
# folder of each GRASS location if you want to change in a new mapset you need to
# define the variable "grass.mapset" after your demands
initGRASS(gisBase=grass.gis.base, home=tempdir(), 
          gisDbase=file.path(root.dir, working.dir), 
          location=grass.loc, mapset=grass.mapset,
          ifelse(["sysname"] == "Windows", use_g.dirseps.exe=FALSE, use_g.dirseps.exe=TRUE)) 
# (3) We need extend, resolution  and coordinates for the EXISTING location & mapset 
# BE CAREFULL this works only if the INPUT FILE CONTAINS TRULY THE SAME projection
# (3a) import raster data in GRASS to obtain the necessary informations
execGRASS('',  flags=c('o',"overwrite"), input=in.dem,  output='rastgrass', band=1)
# (3b) use g.region to put the derived informations into the location settings
execGRASS("g.region",  rast="rastgrass")
# (3b) check it all variables should contain reliable informations

Basically that's it. It looks simple and is simple. However if you should do it exactly in the sequence shown - otherwise your setup may crash or even worse GRASS will do arbitrary things with your data.

Use of spgrass6

The use of the spgrass tool is pretty much straightforward. Actually there are four major functions. Read vector and raster data to R objects, execute generic GRASS command line commands via execGRASS and deal with the environment settings as we have already done using initGRASS. The central interface is execGRASS. The function provides an interface to GRASS commands run through system. You can use the values returned by the –interface flag. Reading vector and raster data can be ommitted due to the much more convenient and powerful raster package.

# import gdal raster data in GRASS
execGRASS('',  flags=c('o',"overwrite"), input=in.dem,  output='grassdem', band=1)
# to derive slope and aspect from the filtered DEM
execGRASS("r.slope.aspect", flags=c("overwrite"), elevation="grassdem", slope="slope", aspect="aspect")

The main benefit of spgrass6

It is a hard piece of work to initialize the interface for the Windows systems. Additionally GRASS is a piece of software that you have to fight for to access. But if you once have understood the GRASS basics you will never miss the power and stability again.

So the main advantage of the spgrass6 package is the plain and straightforward use of the GRASS GIS. As you probably may not like the peculiar GUI of GRASS you will love the GRASS functionality. It is easy to translate both the QGIS generated GRASS commands as well as the originally GRASS generated command line command to the syntax of spgrass6.

Things of further interest

For any help you may use the documentation of spgrass6 or perhaps you prefer the comprehensive and easy to use rdocumentation page.

Christoph Reudenbach 2014/12/27 11:39

r/r-tutorials/spgrass6.txt · Last modified: 2018/12/23 19:46 (external edit)