I want to use GRASS GIS 7 through R 3.1.3 in kubuntu operational system. Could someone help me connect GRASS with R, and use GRASS commands through R (not the other way round!).
2 Answers
Here is a quick worked example of setting the GRASS environment, reading an on-disk raster, calculating a focal mean (using r.neighbors) and reading the results back into R. Hopefully this will get you started.
if (!require(rgrass7)) stop("rgrass7 PACKAGE MISSING")
setwd("D:/TMP") # Working directory
# Set on-disk raster variable
rname <- paste(getwd(), "elev.img", sep="/")
# Set GRASS environment and database location
loc <- initGRASS("C:/Program Files (x86)/GRASS GIS 7.0.0",
home=getwd(), gisDbase="GRASS_TEMP", override=TRUE )
# Import raster to GRASS and set region
execGRASS("r.in.gdal", flags="o", parameters=list(input=rname, output="tmprast"))
execGRASS("g.region", parameters=list(raster="tmprast") )
# Calculate 9x9 focal mean
execGRASS("r.neighbors", flags="overwrite", parameters=list(input="tmprast", output="xxfm",
method="average", size=as.integer(9)) )
r <- readRAST("xxfm")
spplot(r)
-
1When you end (
stop()
) after unsuccessfulrequire()
,library()
might be more appropriate. Jun 9, 2015 at 22:43 -
1works like a charm. if anybody searches for linux path to grass executable: -> /usr/lib/grass72 if you have 7.2 installed. otherwise check with grass<<your version here>> --config path. Note that you need grass-dev package installed as well.– joaoalNov 9, 2017 at 10:47
Thank you very much for your responses! Eventually, is very very easy to work with GRASS GIS through R. After you have created in GRASS the location and mapset in which you wish to work, you can type in the GRASS shell: "rstudio &" "&" Helps for working simultaneously in both GRASS GIS and R. Otherwise, the GRASS shell would switch to R. And that is for Linux!
rgrass7
?initGRASS()
but the rest should be the same (you are still usingexecGRASS()
and others to call GRASS modules etc.