[R-sig-Geo] How to test for a layer in GRASS GIS mapset using rgrass7

Roger Bivand Roger@Biv@nd @ending from nhh@no
Tue Dec 4 20:55:08 CET 2018


On Tue, 4 Dec 2018, Christian Willmes wrote:

> Hello,
>
> I am not sure if this is the correct list to ask this specific question about 
> executing GRASS GIS from R Scripts.
>
> My problem is how to determine if a layer exists in the current GRASS GIS 
> mapset or not.
>
> During my script I use r.mapcalc from GRASS GIS to do some expensive 
> computation. So I want to store and reuse the resulting layer, wich is 
> produced according to a variable value, in case I need this layer for the 
> specific variable value again.
>
> If I just omit the overwrite tag it does not work, becasue GRASS GIS stops 
> the execution on this event.
>
> Error in execGRASS("r.mapcalc", expression = expr) : The command:
> r.mapcalc expression="rsl40 = GEBCO_2014_2D_4326 >= -40"
> produced an error (1) during execution:
> FEHLER: output map <rsl40> exists. To overwrite, use the --overwrite flag
> Error in execGRASS("r.mapcalc", expression = expr) : The command:
> r.mapcalc expression="land_NA_1_rsl40  =  if( rsl40 , 1 ,null())"
> produced an error (1) during execution:
> FEHLER: output map <land_NA_1_rsl40> exists. To overwrite, use the
>         --overwrite flag
>
> So, I tryed to check if a certain layer already exists in the mapset to test 
> if the computation needs/can be executed or not.
>
> Using the following:
>
> if(execGRASS("g.findfile", element="cell", file=lyrname, mapset='"."')){
>     return(FALSE)
>   }else{
>     return(TRUE)
>   }

You need to wrap the test in try() if it may not succeed (in nc):

oo <- try(execGRASS("g.findfile", element="cell", file="slope",
       mapset="'.'", intern=TRUE), silent=TRUE)
ifelse(class(oo) == "try-error", FALSE, TRUE)

and use intern to capture the output if the file exists. However, you can, 
as Rich says, simply overwrite existing files if you wish.

>
> Here it stops, if the layer does not exist:
>

Note that your R script does not stop, simply g.findfile has returned 1 
rather than 0 on exit.

Hope this clarifies,

Roger


> Fehler in execGRASS("g.findfile", element = "cell", file = lyrname, mapset = 
> "\".\"") :
>   The command:
> g.findfile element=cell file=rsl40 mapset="."
> produced an error (1) during execution:
>
>
> Does anyone know a solution to this?
>
> Thank you very much!
>
> Best,
> Christian
>
>
>

-- 
Roger Bivand
Department of Economics, Norwegian School of Economics,
Helleveien 30, N-5045 Bergen, Norway.
voice: +47 55 95 93 55; e-mail: Roger.Bivand using nhh.no
https://orcid.org/0000-0003-2392-6140
https://scholar.google.no/citations?user=AWeghB0AAAAJ&hl=en


More information about the R-sig-Geo mailing list