From fdffcc212d69fb786197915c99526195367f2058 Mon Sep 17 00:00:00 2001 From: Anna Petrasova Date: Fri, 7 Feb 2025 16:53:27 -0500 Subject: [PATCH] R tutorials: fix URLs and text after maintainer change (#13) --- .../fast_track_grass_and_R/execute-results/html.json | 8 +++++--- .../execute-results/html.json | 4 ++-- content/tutorials/get_started/fast_track_grass_and_R.qmd | 6 +++--- .../quick_comparison_r_vs_python_grass_interfaces.qmd | 4 ++-- 4 files changed, 12 insertions(+), 10 deletions(-) diff --git a/_freeze/content/tutorials/get_started/fast_track_grass_and_R/execute-results/html.json b/_freeze/content/tutorials/get_started/fast_track_grass_and_R/execute-results/html.json index 6a7e05c..db512c0 100644 --- a/_freeze/content/tutorials/get_started/fast_track_grass_and_R/execute-results/html.json +++ b/_freeze/content/tutorials/get_started/fast_track_grass_and_R/execute-results/html.json @@ -1,8 +1,10 @@ { - "hash": "69064cce5e8dafbda05baf0404a42fb4", + "hash": "96c142101eb4216f9be231e915104357", "result": { - "markdown": "---\ntitle: \"Get started with GRASS & R: the rgrass package\"\nauthor: \"Veronica Andreo\"\ndate: 2024-03-29\ndate-modified: today\nformat: \n html:\n toc: true\n code-tools: true\n code-copy: true\n code-fold: false\ncategories: [R, rgrass, intermediate] \nengine: knitr\nexecute: \n eval: false\n---\n\n\nThe [**rgrass**](https://cran.r-project.org/web/packages/rgrass/index.html) \npackage allows us to interact with GRASS tools (and data) serving as an\ninterface between GRASS GIS and R.\nThe *rgrass* package is developed and maintained by Roger Bivand and can be \nfound at: . In this fast track tutorial, \nwe will learn how to use GRASS GIS from R.\n\n::: {.callout-note title=\"Setup\"}\nTo run this tutorial locally you should have GRASS GIS 8.4+, \n[R](https://www.r-project.org/) and, optionally, \n[RStudio](https://posit.co/download/rstudio-desktop/) installed. \nYou will also need to install *rgrass*, *terra* and *mapview*\nR packages and download the \n[North Carolina sample dataset](https://grass.osgeo.org/sampledata/north_carolina/nc_basic_spm_grass7.zip).\n:::\n\n## *rgrass* main functions\n\nThe main functions within **rgrass** are the following:\n\n- `initGRASS()`: starts a GRASS session from R.\n- `execGRASS()`: executes GRASS commands from R.\n- `gmeta()`: prints GRASS session metadata like database, project, mapset, computational region settings and CRS.\n- `read_VECT()` and `read_RAST()`: read vector and raster maps from a GRASS project into R.\n- `write_VECT()` and `write_RAST()`: write vector and raster objects from R into a GRASS project.\n\n:::{.callout-note}\nFor further details on *rgrass* functionality, usage examples and data format \ncoercion, see: .\n:::\n\n## Basic usage: Choose your own adventure\n\nIf you are a regular R user that needs to use GRASS GIS functionality \n**because, well, you know it rocks**, rgrass has your back. For example,\nmaybe you struggle with large raster datasets in R or you need some specific \ntool, like watershed delineation for a large high resolution DEM. We will show \nhere the way to use GRASS tools within your R workflows. \n\nOn the other hand, if you already use GRASS as your geospatial data processing \nengine, you most likely have your spatial data within GRASS projects. \nYou might need however to do some statistical analysis, some modelling and \nprediction or create publication ready visualizations in R. In such cases, \nyou can start a GRASS session in your project from R or RStudio.\n\nLet's see the general **basic steps** and then dive into the details:\n\n1. Make sure GRASS GIS is installed.\n2. Open R (or RStudio)\n3. Load `rgrass` library with `library(rgrass)`\n4. Start a GRASS session with `initGRASS()`\n5. Use GRASS tools through `execGRASS()`\n6. Use `read_VECT()`, `read_RAST()`, `write_VECT()` and `write_RAST()` to read data from and write data into GRASS database.\n\n:::{.callout-note}\nGRASS raster and vector maps are translated into *terra*'s package SpatRaster \nand SpatVector objects, respectively. These objects can then, within R, be \neasily coerced to other types of spatial objects such as simple features (sf), \nstars, etc.\n\nSee *terra* vignettes with further explanations and examples: \n.\n:::\n\n### A. Use GRASS GIS tools within your R spatial workflows\n\nWe start R or Rstudio and load the `rgrass` library. It will tell us that GRASS \nis not running, but we know that already... and that's about to change in a \nmoment.\n\n\n::: {.cell}\n\n```{.r .cell-code}\nlibrary(rgrass)\n```\n:::\n\n\nIn case you need to include some of the cool GRASS tools within your\nR workflow, the `initGRASS()` function allows you to create temporary GRASS \nprojects to use GRASS tools on R objects. \nThis is equivalent to what QGIS does when you use GRASS tools via the \nQGIS Processing Toolbox.\n\nFirst, we will use `initGRASS()` to create a temporary \nGRASS project based on the extent, resolution and CRS of a raster or vector R object, \nlikely the one we want to process or one that has the extent of our study area. \nHence, we need to pass a reference spatial grid via the *SG* parameter. \nThen, we will write our R objects into the temporary GRASS project, run the desired \nprocesses, and export the outputs back to the R environment.\n\nLet's start with getting some spatial data, e.g., a raster file, into R.\n\n\n::: {.cell}\n\n```{.r .cell-code}\nlibrary(terra)\nf <- system.file(\"ex/elev.tif\", package=\"terra\")\nr <- rast(f)\nplot(r)\n```\n:::\n\n\nNow, we will start GRASS GIS in a temporary folder. By specifying `SG = r`,\nthe GRASS project is internally created with raster `r`'s object CRS (BTW,\nyou can check that with `crs(r)`), extent and resolution.\nThese latter define the GRASS computational region that will affect all raster\nprocessing, i.e., all new raster maps generated within GRASS GIS will have the\nsame extent and resolution of the map provided. \nIf you wish to change the computational region later on, you can use the \n`g.region` GRASS tool with `execGRASS(\"g.region --h\")`.\n\nOptionally, we can specify which GRASS binary to use with `gisBase`. This might\nbe useful in case we have several GRASS versions on our system. If not provided,\n`initGRASS()` will attempt to find it in default locations depending on your\noperating system.\n\n\n::: {.cell}\n\n```{.r .cell-code}\n# Start GRASS GIS from R\ninitGRASS(home = tempdir(),\n SG = r, \n override = TRUE)\n```\n:::\n\n\nNow, we can write our SpatRaster into the GRASS temporary project.\n\n\n::: {.cell}\n\n```{.r .cell-code}\nwrite_RAST(r, \"terra_elev\")\n```\n:::\n\n\nAlternatively, we can use GRASS importing tools to import common raster and\nvector formats. Data will be reprojected if needed.\n\n\n::: {.cell}\n\n```{.r .cell-code}\nexecGRASS(\"r.import\", input=f, output=\"test\")\n```\n:::\n\n\nLet's check both raster maps (`test` and `terra_elev`) are indeed within\nthe project and run the GRASS tool \n[`r.slope.aspect`](https://grass.osgeo.org/grass-stable/manuals/r.slope.aspect.html)\non one of them.\n\n\n::: {.cell}\n\n```{.r .cell-code}\nexecGRASS(\"g.list\", type = \"raster\")\n```\n:::\n\n::: {.cell}\n\n```{.r .cell-code}\nexecGRASS(\"r.slope.aspect\", \n elevation = \"terra_elev\", \n slope = \"slope\",\n aspect = \"aspect\")\n```\n:::\n\n::: {.cell}\n\n```{.r .cell-code}\nexecGRASS(\"g.list\", type = \"raster\")\n```\n:::\n\n\nLet's get slope and aspect maps into R\n\n\n::: {.cell}\n\n```{.r .cell-code}\ngrass_maps <- read_RAST(c(\"aspect\", \"slope\"))\ngrass_maps\n```\n:::\n\n\nNow that the output maps are back into our R environment, we can plot them, do\nfurther analysis or write them into other raster formats, in which case we use\n`terra::writeRaster()` function.\n\n\n::: {.cell}\n\n```{.r .cell-code}\nplot(grass_maps)\n```\n:::\n\n\n![](images/R_aspect_slope.png){.preview-image width=60%}\n\n\n::: {.cell}\n\n```{.r .cell-code}\nwriteRaster(grass_maps, \"grass_maps.tif\", overwrite=TRUE)\n```\n:::\n\n\nAlternatively, we can use GRASS GIS exporting tools like \n[r.out.gdal](https://grass.osgeo.org/grass-stable/manuals/r.out.gdal.html) \nand [v.out.ogr](https://grass.osgeo.org/grass-stable/manuals/v.out.ogr.html), \nto directly save our outputs into common raster or vector formats, respectively.\n\n\n::: {.cell}\n\n```{.r .cell-code}\nexecGRASS(\"r.out.gdal\", input=\"slope\", output=\"slope.tif\", format=\"GTiff\", flags=\"overwrite\")\n```\n:::\n\n\n\n### B. Use R tools within GRASS GIS workflows\n\nLet's see an example for the case when we do our geospatial data processing \nwithin GRASS GIS and hence have all the spatial data organized within GRASS projects\nbut we need to run some statistical analysis, modelling, prediction \nor visualization in R.\n\n\n::: {.cell}\n\n```{.r .cell-code}\nlibrary(rgrass)\n```\n:::\n\n\nWe start GRASS GIS from within R or RStudio using the `initGRASS()` function. \nSince we want to start GRASS GIS in a specific project and mapset, we need to\nspecify them.\n\n\n::: {.cell}\n\n```{.r .cell-code}\n# Start GRASS GIS from R\ninitGRASS(gisDbase = path.expand(\"~/grassdata/\"),\n location = \"nc_basic_spm_grass7\",\n mapset = \"PERMANENT\",\n override = TRUE,\n remove_GISRC = TRUE)\n```\n:::\n\n\nWe can now list and read our GRASS raster and vector maps into R and do our \nstatistical analysis, modelling and/or visualizations using other R packages. \nHere, we will demonstrate the use of all the main *rgrass* functions \nmentioned above.\n\nLet's then list our GRASS raster and vector maps:\n\n\n::: {.cell}\n\n```{.r .cell-code}\n# List GRASS raster maps\nexecGRASS(\"g.list\", type=\"raster\")\n```\n:::\n\n::: {.cell}\n\n```{.r .cell-code}\n# List GRASS vector maps\nexecGRASS(\"g.list\", type=\"vector\")\n```\n:::\n\n\nThe resulting map lists could be saved in an R object that we can subset later \nin case we want to import several but not all raster maps, for example. Let's \nsee how to do that.\n\n\n::: {.cell}\n\n```{.r .cell-code}\n# Save map list in an object\nrast_list <- execGRASS(\"g.list\", type=\"raster\")\n\n# Retrieve only the map list from standard output\nrast_list <- attributes(rast_list)$resOut\n\n# Import elevation and landuse\nto_import <- c(\"elevation\", \"landuse\") # optionally, by position: rast_list[c(3,7)]\n\nmaplist <- list()\nfor (i in to_import) {\n maplist[[i]] <- read_RAST(i)\n}\n\nmaplist\n```\n:::\n\n\nRemember that raster objects will always be exported from GRASS GIS following the \n*computational region settings*. So, bear that in mind when reading into R which \nwill hold them in memory. Vectors however will be exported in their full extent.\n\nLet's load the *terra* library to quickly display our recently imported raster \nmaps:\n\n\n::: {.cell}\n\n```{.r .cell-code}\nlibrary(terra)\nplot(maplist$elevation)\n```\n:::\n\n\nOptionally, we could stack our two `SpatRaster` objects together and plot them \ntogether:\n\n\n::: {.cell}\n\n```{.r .cell-code}\nrstack <- rast(maplist)\nplot(rstack)\n```\n:::\n\n\nLet's create a boxplot of elevation per land class.\n\n\n::: {.cell}\n\n```{.r .cell-code}\nboxplot(rstack$elevation, rstack$landuse, maxcell=50000)\n```\n:::\n\n\nLet's import a vector map, too, and explore its attributes.\n\n\n::: {.cell}\n\n```{.r .cell-code}\ncensus <- read_VECT(\"census\")\nhead(census)\n```\n:::\n\n::: {.cell}\n\n```{.r .cell-code}\nsummary(census$TOTAL_POP)\n```\n:::\n\n::: {.cell}\n\n```{.r .cell-code}\nplot(census, \"P25_TO_34\", type=\"interval\", breaks=5, plg=list(x=\"topright\"))\n```\n:::\n\n\nLet's do some interactive visualization with `mapview`.\n\n\n::: {.cell}\n\n```{.r .cell-code}\nlibrary(mapview)\nmapview(rstack$elevation) + census\n```\n:::\n\n\nWe highly recommend you to check the [tmap](https://r-tmap.github.io/tmap/) \npackage to make really appealing and publication ready maps.\n\nTo exemplify the use of `write_*` functions, let's do a simple operation with \nthe *landuse* raster map. We will apply a custom function that makes NULL all \nvalues less than 4.\n\n\n::: {.cell}\n\n```{.r .cell-code}\nresult <- app(rstack$landuse, fun=function(x){ x[x < 4] <- NA; return(x)} )\nplot(result)\n```\n:::\n\n\nTo use this new raster in GRASS GIS, for example as an input to a GRASS tool, we need to call `write_RAST` function:\n\n::: {.cell}\n\n```{.r .cell-code}\nwrite_RAST(result, \"result_from_R\", overwrite = TRUE)\n```\n:::\n\n\nThe new raster is now written as a GRASS raster and can be listed:\n\n::: {.cell}\n\n```{.r .cell-code}\nexecGRASS(\"g.list\", parameters = list(type=\"raster\", pattern=\"result*\"))\n```\n:::\n\n\n\nFinally, there is yet another way in which you can use GRASS and R together, and it \ninvolves calling R from the GRASS terminal. In this way, *rgrass* will read all \nGRASS session environmental variables, and you won't need to use \n`initGRASS()`. It goes more or less like this:\n\n1. Open GRASS GIS\n2. Type `R` or `rstudio &` in the GRASS terminal\n3. Load `rgrass` library with `library(rgrass)`\n4. Use `read_VECT()`, `read_RAST()` to read data from GRASS GIS into R\n5. Do your analysis or plotting in R\n6. Write data (back) to GRASS database with `write_VECT()` and `write_RAST()`\n7. Quit R `quit()` and get back to GRASS terminal.\n\n``` \nStarting GRASS GIS...\n\n __________ ___ __________ _______________\n / ____/ __ \\/ | / ___/ ___/ / ____/ _/ ___/\n / / __/ /_/ / /| | \\__ \\\\_ \\ / / __ / / \\__ \\\n / /_/ / _, _/ ___ |___/ /__/ / / /_/ // / ___/ /\n \\____/_/ |_/_/ |_/____/____/ \\____/___//____/\n\nWelcome to GRASS GIS 8.4.0\nGRASS GIS homepage: https://grass.osgeo.org\nThis version running through: Bash Shell (/bin/bash)\nHelp is available with the command: g.manual -i\nSee the licence terms with: g.version -c\nSee citation options with: g.version -x\nIf required, restart the GUI with: g.gui wxpython\nWhen ready to quit enter: exit\n\nLaunching GUI in the background, please wait...\n[Raster MASK present]\nGRASS nc_basic_spm_grass7/PERMANENT:~ > R\n\nR version 4.3.1 (2023-06-16) -- \"Beagle Scouts\"\nCopyright (C) 2023 The R Foundation for Statistical Computing\nPlatform: x86_64-pc-linux-gnu (64-bit)\n\nR is free software and comes with ABSOLUTELY NO WARRANTY.\nYou are welcome to redistribute it under certain conditions.\nType 'license()' or 'licence()' for distribution details.\n\n Natural language support but running in an English locale\n\nR is a collaborative project with many contributors.\nType 'contributors()' for more information and\n'citation()' on how to cite R or R packages in publications.\n\nType 'demo()' for some demos, 'help()' for on-line help, or\n'help.start()' for an HTML browser interface to help.\nType 'q()' to quit R.\n\n> library(rgrass)\nGRASS GIS interface loaded with GRASS version: GRASS 8.4.0 (2024)\nand location: nc_basic_spm_grass7\n> \n```\n\n**Enjoy!** {{< fa rocket >}}\n\n\n## References\n\n- Bivand R (2024).\n_rgrass: Interface Between 'GRASS' Geographical Information System and 'R'_. \nR package version 0.4-1, .\n\n\n***\n\n:::{.smaller}\nThe development of this tutorial was funded by the US \n[National Science Foundation (NSF)](https://www.nsf.gov/), \naward [2303651](https://www.nsf.gov/awardsearch/showAward?AWD_ID=2303651).\n:::\n", - "supporting": [], + "markdown": "---\ntitle: \"Get started with GRASS & R: the rgrass package\"\nauthor: \"Veronica Andreo\"\ndate: 2024-03-29\ndate-modified: today\nformat: \n html:\n toc: true\n code-tools: true\n code-copy: true\n code-fold: false\ncategories: [R, rgrass, intermediate] \nengine: knitr\nexecute: \n eval: false\n---\n\n\nThe [**rgrass**](https://cran.r-project.org/web/packages/rgrass/index.html) \npackage allows us to interact with GRASS tools (and data) serving as an\ninterface between GRASS GIS and R.\nThe *rgrass* package source code can be\nfound at: . In this fast track tutorial,\nwe will learn how to use GRASS GIS from R.\n\n::: {.callout-note title=\"Setup\"}\nTo run this tutorial locally you should have GRASS GIS 8.4+, \n[R](https://www.r-project.org/) and, optionally, \n[RStudio](https://posit.co/download/rstudio-desktop/) installed. \nYou will also need to install *rgrass*, *terra* and *mapview*\nR packages and download the \n[North Carolina sample dataset](https://grass.osgeo.org/sampledata/north_carolina/nc_basic_spm_grass7.zip).\n:::\n\n## *rgrass* main functions\n\nThe main functions within **rgrass** are the following:\n\n- `initGRASS()`: starts a GRASS session from R.\n- `execGRASS()`: executes GRASS commands from R.\n- `gmeta()`: prints GRASS session metadata like database, project, mapset, computational region settings and CRS.\n- `read_VECT()` and `read_RAST()`: read vector and raster maps from a GRASS project into R.\n- `write_VECT()` and `write_RAST()`: write vector and raster objects from R into a GRASS project.\n\n:::{.callout-note}\nFor further details on *rgrass* functionality, usage examples and data format \ncoercion, see: .\n:::\n\n## Basic usage: Choose your own adventure\n\nIf you are a regular R user that needs to use GRASS GIS functionality \n**because, well, you know it rocks**, rgrass has your back. For example,\nmaybe you struggle with large raster datasets in R or you need some specific \ntool, like watershed delineation for a large high resolution DEM. We will show \nhere the way to use GRASS tools within your R workflows. \n\nOn the other hand, if you already use GRASS as your geospatial data processing \nengine, you most likely have your spatial data within GRASS projects. \nYou might need however to do some statistical analysis, some modelling and \nprediction or create publication ready visualizations in R. In such cases, \nyou can start a GRASS session in your project from R or RStudio.\n\nLet's see the general **basic steps** and then dive into the details:\n\n1. Make sure GRASS GIS is installed.\n2. Open R (or RStudio)\n3. Load `rgrass` library with `library(rgrass)`\n4. Start a GRASS session with `initGRASS()`\n5. Use GRASS tools through `execGRASS()`\n6. Use `read_VECT()`, `read_RAST()`, `write_VECT()` and `write_RAST()` to read data from and write data into GRASS database.\n\n:::{.callout-note}\nGRASS raster and vector maps are translated into *terra*'s package SpatRaster \nand SpatVector objects, respectively. These objects can then, within R, be \neasily coerced to other types of spatial objects such as simple features (sf), \nstars, etc.\n\nSee *terra* vignettes with further explanations and examples: \n.\n:::\n\n### A. Use GRASS GIS tools within your R spatial workflows\n\nWe start R or Rstudio and load the `rgrass` library. It will tell us that GRASS \nis not running, but we know that already... and that's about to change in a \nmoment.\n\n\n::: {.cell}\n\n```{.r .cell-code}\nlibrary(rgrass)\n```\n:::\n\n\nIn case you need to include some of the cool GRASS tools within your\nR workflow, the `initGRASS()` function allows you to create temporary GRASS \nprojects to use GRASS tools on R objects. \nThis is equivalent to what QGIS does when you use GRASS tools via the \nQGIS Processing Toolbox.\n\nFirst, we will use `initGRASS()` to create a temporary \nGRASS project based on the extent, resolution and CRS of a raster or vector R object, \nlikely the one we want to process or one that has the extent of our study area. \nHence, we need to pass a reference spatial grid via the *SG* parameter. \nThen, we will write our R objects into the temporary GRASS project, run the desired \nprocesses, and export the outputs back to the R environment.\n\nLet's start with getting some spatial data, e.g., a raster file, into R.\n\n\n::: {.cell}\n\n```{.r .cell-code}\nlibrary(terra)\nf <- system.file(\"ex/elev.tif\", package=\"terra\")\nr <- rast(f)\nplot(r)\n```\n:::\n\n\nNow, we will start GRASS GIS in a temporary folder. By specifying `SG = r`,\nthe GRASS project is internally created with raster `r`'s object CRS (BTW,\nyou can check that with `crs(r)`), extent and resolution.\nThese latter define the GRASS computational region that will affect all raster\nprocessing, i.e., all new raster maps generated within GRASS GIS will have the\nsame extent and resolution of the map provided. \nIf you wish to change the computational region later on, you can use the \n`g.region` GRASS tool with `execGRASS(\"g.region --h\")`.\n\nOptionally, we can specify which GRASS binary to use with `gisBase`. This might\nbe useful in case we have several GRASS versions on our system. If not provided,\n`initGRASS()` will attempt to find it in default locations depending on your\noperating system.\n\n\n::: {.cell}\n\n```{.r .cell-code}\n# Start GRASS GIS from R\ninitGRASS(home = tempdir(),\n SG = r, \n override = TRUE)\n```\n:::\n\n\nNow, we can write our SpatRaster into the GRASS temporary project.\n\n\n::: {.cell}\n\n```{.r .cell-code}\nwrite_RAST(r, \"terra_elev\")\n```\n:::\n\n\nAlternatively, we can use GRASS importing tools to import common raster and\nvector formats. Data will be reprojected if needed.\n\n\n::: {.cell}\n\n```{.r .cell-code}\nexecGRASS(\"r.import\", input=f, output=\"test\")\n```\n:::\n\n\nLet's check both raster maps (`test` and `terra_elev`) are indeed within\nthe project and run the GRASS tool \n[`r.slope.aspect`](https://grass.osgeo.org/grass-stable/manuals/r.slope.aspect.html)\non one of them.\n\n\n::: {.cell}\n\n```{.r .cell-code}\nexecGRASS(\"g.list\", type = \"raster\")\n```\n:::\n\n::: {.cell}\n\n```{.r .cell-code}\nexecGRASS(\"r.slope.aspect\", \n elevation = \"terra_elev\", \n slope = \"slope\",\n aspect = \"aspect\")\n```\n:::\n\n::: {.cell}\n\n```{.r .cell-code}\nexecGRASS(\"g.list\", type = \"raster\")\n```\n:::\n\n\nLet's get slope and aspect maps into R\n\n\n::: {.cell}\n\n```{.r .cell-code}\ngrass_maps <- read_RAST(c(\"aspect\", \"slope\"))\ngrass_maps\n```\n:::\n\n\nNow that the output maps are back into our R environment, we can plot them, do\nfurther analysis or write them into other raster formats, in which case we use\n`terra::writeRaster()` function.\n\n\n::: {.cell}\n\n```{.r .cell-code}\nplot(grass_maps)\n```\n:::\n\n\n![](images/R_aspect_slope.png){.preview-image width=60%}\n\n\n::: {.cell}\n\n```{.r .cell-code}\nwriteRaster(grass_maps, \"grass_maps.tif\", overwrite=TRUE)\n```\n:::\n\n\nAlternatively, we can use GRASS GIS exporting tools like \n[r.out.gdal](https://grass.osgeo.org/grass-stable/manuals/r.out.gdal.html) \nand [v.out.ogr](https://grass.osgeo.org/grass-stable/manuals/v.out.ogr.html), \nto directly save our outputs into common raster or vector formats, respectively.\n\n\n::: {.cell}\n\n```{.r .cell-code}\nexecGRASS(\"r.out.gdal\", input=\"slope\", output=\"slope.tif\", format=\"GTiff\", flags=\"overwrite\")\n```\n:::\n\n\n\n### B. Use R tools within GRASS GIS workflows\n\nLet's see an example for the case when we do our geospatial data processing \nwithin GRASS GIS and hence have all the spatial data organized within GRASS projects\nbut we need to run some statistical analysis, modelling, prediction \nor visualization in R.\n\n\n::: {.cell}\n\n```{.r .cell-code}\nlibrary(rgrass)\n```\n:::\n\n\nWe start GRASS GIS from within R or RStudio using the `initGRASS()` function. \nSince we want to start GRASS GIS in a specific project and mapset, we need to\nspecify them.\n\n\n::: {.cell}\n\n```{.r .cell-code}\n# Start GRASS GIS from R\ninitGRASS(gisDbase = path.expand(\"~/grassdata/\"),\n location = \"nc_basic_spm_grass7\",\n mapset = \"PERMANENT\",\n override = TRUE,\n remove_GISRC = TRUE)\n```\n:::\n\n\nWe can now list and read our GRASS raster and vector maps into R and do our \nstatistical analysis, modelling and/or visualizations using other R packages. \nHere, we will demonstrate the use of all the main *rgrass* functions \nmentioned above.\n\nLet's then list our GRASS raster and vector maps:\n\n\n::: {.cell}\n\n```{.r .cell-code}\n# List GRASS raster maps\nexecGRASS(\"g.list\", type=\"raster\")\n```\n:::\n\n::: {.cell}\n\n```{.r .cell-code}\n# List GRASS vector maps\nexecGRASS(\"g.list\", type=\"vector\")\n```\n:::\n\n\nThe resulting map lists could be saved in an R object that we can subset later \nin case we want to import several but not all raster maps, for example. Let's \nsee how to do that.\n\n\n::: {.cell}\n\n```{.r .cell-code}\n# Save map list in an object\nrast_list <- execGRASS(\"g.list\", type=\"raster\")\n\n# Retrieve only the map list from standard output\nrast_list <- attributes(rast_list)$resOut\n\n# Import elevation and landuse\nto_import <- c(\"elevation\", \"landuse\") # optionally, by position: rast_list[c(3,7)]\n\nmaplist <- list()\nfor (i in to_import) {\n maplist[[i]] <- read_RAST(i)\n}\n\nmaplist\n```\n:::\n\n\nRemember that raster objects will always be exported from GRASS GIS following the \n*computational region settings*. So, bear that in mind when reading into R which \nwill hold them in memory. Vectors however will be exported in their full extent.\n\nLet's load the *terra* library to quickly display our recently imported raster \nmaps:\n\n\n::: {.cell}\n\n```{.r .cell-code}\nlibrary(terra)\nplot(maplist$elevation)\n```\n:::\n\n\nOptionally, we could stack our two `SpatRaster` objects together and plot them \ntogether:\n\n\n::: {.cell}\n\n```{.r .cell-code}\nrstack <- rast(maplist)\nplot(rstack)\n```\n:::\n\n\nLet's create a boxplot of elevation per land class.\n\n\n::: {.cell}\n\n```{.r .cell-code}\nboxplot(rstack$elevation, rstack$landuse, maxcell=50000)\n```\n:::\n\n\nLet's import a vector map, too, and explore its attributes.\n\n\n::: {.cell}\n\n```{.r .cell-code}\ncensus <- read_VECT(\"census\")\nhead(census)\n```\n:::\n\n::: {.cell}\n\n```{.r .cell-code}\nsummary(census$TOTAL_POP)\n```\n:::\n\n::: {.cell}\n\n```{.r .cell-code}\nplot(census, \"P25_TO_34\", type=\"interval\", breaks=5, plg=list(x=\"topright\"))\n```\n:::\n\n\nLet's do some interactive visualization with `mapview`.\n\n\n::: {.cell}\n\n```{.r .cell-code}\nlibrary(mapview)\nmapview(rstack$elevation) + census\n```\n:::\n\n\nWe highly recommend you to check the [tmap](https://r-tmap.github.io/tmap/) \npackage to make really appealing and publication ready maps.\n\nTo exemplify the use of `write_*` functions, let's do a simple operation with \nthe *landuse* raster map. We will apply a custom function that makes NULL all \nvalues less than 4.\n\n\n::: {.cell}\n\n```{.r .cell-code}\nresult <- app(rstack$landuse, fun=function(x){ x[x < 4] <- NA; return(x)} )\nplot(result)\n```\n:::\n\n\nTo use this new raster in GRASS GIS, for example as an input to a GRASS tool, we need to call `write_RAST` function:\n\n::: {.cell}\n\n```{.r .cell-code}\nwrite_RAST(result, \"result_from_R\", overwrite = TRUE)\n```\n:::\n\n\nThe new raster is now written as a GRASS raster and can be listed:\n\n::: {.cell}\n\n```{.r .cell-code}\nexecGRASS(\"g.list\", parameters = list(type=\"raster\", pattern=\"result*\"))\n```\n:::\n\n\n\nFinally, there is yet another way in which you can use GRASS and R together, and it \ninvolves calling R from the GRASS terminal. In this way, *rgrass* will read all \nGRASS session environmental variables, and you won't need to use \n`initGRASS()`. It goes more or less like this:\n\n1. Open GRASS GIS\n2. Type `R` or `rstudio &` in the GRASS terminal\n3. Load `rgrass` library with `library(rgrass)`\n4. Use `read_VECT()`, `read_RAST()` to read data from GRASS GIS into R\n5. Do your analysis or plotting in R\n6. Write data (back) to GRASS database with `write_VECT()` and `write_RAST()`\n7. Quit R `quit()` and get back to GRASS terminal.\n\n``` \nStarting GRASS GIS...\n\n __________ ___ __________ _______________\n / ____/ __ \\/ | / ___/ ___/ / ____/ _/ ___/\n / / __/ /_/ / /| | \\__ \\\\_ \\ / / __ / / \\__ \\\n / /_/ / _, _/ ___ |___/ /__/ / / /_/ // / ___/ /\n \\____/_/ |_/_/ |_/____/____/ \\____/___//____/\n\nWelcome to GRASS GIS 8.4.0\nGRASS GIS homepage: https://grass.osgeo.org\nThis version running through: Bash Shell (/bin/bash)\nHelp is available with the command: g.manual -i\nSee the licence terms with: g.version -c\nSee citation options with: g.version -x\nIf required, restart the GUI with: g.gui wxpython\nWhen ready to quit enter: exit\n\nLaunching GUI in the background, please wait...\n[Raster MASK present]\nGRASS nc_basic_spm_grass7/PERMANENT:~ > R\n\nR version 4.3.1 (2023-06-16) -- \"Beagle Scouts\"\nCopyright (C) 2023 The R Foundation for Statistical Computing\nPlatform: x86_64-pc-linux-gnu (64-bit)\n\nR is free software and comes with ABSOLUTELY NO WARRANTY.\nYou are welcome to redistribute it under certain conditions.\nType 'license()' or 'licence()' for distribution details.\n\n Natural language support but running in an English locale\n\nR is a collaborative project with many contributors.\nType 'contributors()' for more information and\n'citation()' on how to cite R or R packages in publications.\n\nType 'demo()' for some demos, 'help()' for on-line help, or\n'help.start()' for an HTML browser interface to help.\nType 'q()' to quit R.\n\n> library(rgrass)\nGRASS GIS interface loaded with GRASS version: GRASS 8.4.0 (2024)\nand location: nc_basic_spm_grass7\n> \n```\n\n**Enjoy!** {{< fa rocket >}}\n\n\n## References\n\n- Bivand R (2024).\n_rgrass: Interface Between 'GRASS' Geographical Information System and 'R'_. \nR package version 0.4-1, .\n\n\n***\n\n:::{.smaller}\nThe development of this tutorial was funded by the US \n[National Science Foundation (NSF)](https://www.nsf.gov/), \naward [2303651](https://www.nsf.gov/awardsearch/showAward?AWD_ID=2303651).\n:::\n", + "supporting": [ + "fast_track_grass_and_R_files" + ], "filters": [ "rmarkdown/pagebreak.lua" ], diff --git a/_freeze/content/tutorials/r_python_interfaces_comparison/quick_comparison_r_vs_python_grass_interfaces/execute-results/html.json b/_freeze/content/tutorials/r_python_interfaces_comparison/quick_comparison_r_vs_python_grass_interfaces/execute-results/html.json index ee88b58..9bf0817 100644 --- a/_freeze/content/tutorials/r_python_interfaces_comparison/quick_comparison_r_vs_python_grass_interfaces/execute-results/html.json +++ b/_freeze/content/tutorials/r_python_interfaces_comparison/quick_comparison_r_vs_python_grass_interfaces/execute-results/html.json @@ -1,7 +1,7 @@ { - "hash": "b2f5b1384f95aeb0e0a837650dceb10c", + "hash": "2a374eef182ba9763473205048a8489c", "result": { - "markdown": "---\ntitle: \"Quick comparison: R and Python GRASS interfaces\"\nauthor: \"Veronica Andreo\"\ndate: 2024-04-01\ndate-modified: today\nformat:\n html:\n toc: true\n code-tools: true\n code-copy: true\n code-fold: false\ncategories: [Python, R, intermediate]\nengine: knitr\nexecute:\n eval: false\n---\n\n\n![](images/R_Python_compare.png){.preview-image width=50%}\n\nIn this short tutorial we will highlight the similarities of R and Python GRASS interfaces\nin order to streamline the use of GRASS GIS within R and Python communities.\nAs you may know, there's\nan R package called [rgrass](https://github.com/rsbivand/rgrass/) that provides\nbasic functionality to read and write data from and into GRASS database as well\nas to execute GRASS tools in either existing or temporary GRASS projects.\nThe [GRASS Python API](https://grass.osgeo.org/grass-stable/manuals/libpython/index.html),\non the other hand, is composed of various packages that provide classes and\nfunctions for low and high level tasks, including those that can be executed\nwith rgrass.\n\n\n\nThere are some parallelisms between the\n**rgrass** and **grass.script**/**grass.jupyter** packages, i.e.,\nR and Python interfaces to GRASS GIS.\nLet's review them and go through some examples.\n\n\n| Task | rgrass function | GRASS Python API function |\n|------------------------------------------------------------|--------------------------------|---------------------------------------------------------|\n| Load library | library(rgrass) | import grass.script as gs
import grass.jupyter as gj |\n| Start GRASS and set all needed
environmental variables | initGRASS() | gs.setup.init() for scripts,
gj.init() for notebooks |\n| Execute GRASS commands | execGRASS() | gs.run_command(),
gs.read_command(),
gs.parse_command() |\n| Read raster and vector data
from GRASS | read_RAST(),
read_VECT() | gs.array.array(),
n/a |\n| Write raster and vector data
into GRASS | write_RAST(),
write_VECT() | gs.array.write(),
n/a |\n| Get raster and vector info | n/a,
vInfo() | gs.raster_info(),
gs.vector_info() |\n| Close GRASS session | unlink_.gislock() | gs.setup.finish(),
gj.finish() |\n\n: R and Python GRASS interfaces compared {.striped .hover}\n\n## Comparison examples\n\nLet's see how usage examples would look like.\n\n1. **Load the library**: We need to\nload the libraries that allow us to interface with GRASS GIS\nfunctionality and (optionally) data. For the Python case, we first need to add\nthe GRASS python package path to our system's path.\n\n::: {.panel-tabset}\n\n## R\n\n\n::: {.cell}\n\n```{.r .cell-code}\nlibrary(rgrass)\n```\n:::\n\n\n## Python\n\n\n::: {.cell python.reticulate='false'}\n\n```{.python .cell-code}\nimport sys\nimport subprocess\n\nsys.path.append(\n subprocess.check_output([\"grass\", \"--config\", \"python_path\"], text=True).strip()\n)\n\nimport grass.script as gs\nimport grass.jupyter as gj\n```\n:::\n\n\n:::\n\n2. **Start a GRASS session**: Once we loaded or imported the packages, we\nstart a GRASS session. We need to pass the path to a\ntemporary or existing GRASS project.\nIn the case of R, `initGRASS` will automatically look for GRASS binaries, alternatively we can\nspecify the path to the binaries ourselves.\nIn the case of Python, it is worth noting that while grass.script and grass.jupyter init functions\ntake the same arguments, `gj.init` also sets other environmental variables to\nstreamline work within Jupyter Notebooks, e.g., overwrite is set to true so cells\ncan be executed multiple times.\n\n::: {.panel-tabset}\n\n## R\n\n\n::: {.cell}\n\n```{.r .cell-code}\nsession <- initGRASS(gisBase = \"/usr/lib/grass84\", # where grass binaries live, `grass --config path`\n gisDbase = \"/home/user/grassdata\", # path to grass database or folder where your project lives\n location = \"nc_basic_spm_grass7\", # existing project name\n mapset = \"PERMANENT\" # mapset name\n )\n```\n:::\n\n\n## Python\n\n\n::: {.cell python.reticulate='false'}\n\n```{.python .cell-code}\n# With grass.script for scripts\nsession = gs.setup.init(path=\"/home/user/grassdata\",\n location=\"nc_basic_spm_grass7\",\n mapset=\"PERMANENT\")\n# Optionally, the path to a mapset\nsession = gs.setup.init(\"/home/user/grassdata/nc_basic_spm_grass7/PERMANENT\")\n\n# With grass.jupyter for notebooks\nsession = gj.init(path=\"/home/user/grassdata\",\n location=\"nc_basic_spm_grass7\",\n mapset=\"PERMANENT\")\n# Optionally, the path to a mapset\nsession = gj.init(\"~/grassdata/nc_basic_spm_grass7/PERMANENT\")\n```\n:::\n\n\n:::\n\n3. **Execute GRASS commands**: Both interfaces work pretty similarly, the\nfirst argument is always the GRASS tool name and then we pass the parameters\nand flags. While in R we basically use `execGRASS()` for all GRASS commands, in\nthe Python API, we have different wrappers to execute GRASS commands depending\non the nature of their output.\n\n::: {.panel-tabset}\n\n## R\n\n\n::: {.cell}\n\n```{.r .cell-code}\n# Map output\nexecGRASS(\"r.slope.aspect\",\n elevation = \"elevation\",\n slope = \"slope\",\n aspect = \"aspect\")\n\n# Text output\nexecGRASS(\"g.region\",\n raster = \"elevation\",\n flags = \"p\")\n```\n:::\n\n\n## Python\n\n\n::: {.cell python.reticulate='false'}\n\n```{.python .cell-code}\n# Map output\ngs.run_command(\"r.slope.aspect\",\n elevation=\"elevation\",\n slope=\"slope\",\n aspect=\"aspect\")\n# Text output\nprint(gs.read_command(\"g.region\",\n raster=\"elevation\",\n flags=\"p\"))\n# Text output - dictionary\nregion = gs.parse_command(\"g.region\",\n raster=\"elevation\",\n flags=\"g\")\nregion\n```\n:::\n\n\n:::\n\n4. **Read raster and vector data into other R or Python formats**:\n*rgrass* functions `read_RAST()` and `read_VECT()` convert GRASS raster and\nvector maps into terra's SpatRaster and SpatVector objects within R.\nIn the case of Python, GRASS\nraster maps that can be converted into numpy arrays through\n`gs.array.array()`. Vector attribute data can be converted into\nPandas data frames in various ways.\n\n::: {.panel-tabset}\n\n## R\n\n\n::: {.cell}\n\n```{.r .cell-code}\n# Raster\nelevr <- read_RAST(\"elevation\")\n\n# Vector\nschoolsr <- read_VECT(\"schools\")\n```\n:::\n\n\n## Python\n\n\n::: {.cell python.reticulate='false'}\n\n```{.python .cell-code}\n# Raster into numpy array\nelev = gs.array.array(\"elevation\")\n\n# Vector attributes\nimport pandas as pd\nschools = gs.parse_command(\"v.db.select\", map=\"schools\", format=\"json\")\npd.DataFrame(schools[\"records\"])\n\n# Vector geometry and attributes to GeoJSON\ngs.run_command(\"v.out.ogr\", input=\"schools\", output=\"schools.geojson\", format=\"GeoJSON\")\n```\n:::\n\n\n:::\n\n\n5. **Write R or Python objects into GRASS raster and vector maps**: R terra's\nSpatRaster and SpatVector objects can be written (back) into GRASS format with\n`write_RAST()` and `write_VECT()` functions. Within the Python environment,\nnumpy arrays can also be written (back) into GRASS raster maps with the\n`write()` method.\n\n::: {.panel-tabset}\n\n## R\n\n\n::: {.cell}\n\n```{.r .cell-code}\n# Raster\nwrite_RAST(elevr, \"elevation_r\")\n\n# Vector\nwrite_VECT(schoolsr, \"schools_r\")\n```\n:::\n\n\n## Python\n\n\n::: {.cell python.reticulate='false'}\n\n```{.python .cell-code}\n# Raster\nelev.write(mapname=\"elev_np\", overwrite=True)\n\n# GeoJSON into GRASS vector\ngs.run_command(\"v.in.ogr\", input=\"schools.geojson\", output=\"schools2\")\n```\n:::\n\n\n:::\n\n\n6. **Close GRASS GIS session**: In general, just closing R or Rstudio, as well\nas shutting down Jupyter notebook, will clean up and close the GRASS session\nproperly. Sometimes, however, especially if the user changed mapset within the\nworkflow, it is better to clean up explicitly before closing.\n\n::: {.panel-tabset}\n\n## R\n\n\n::: {.cell}\n\n```{.r .cell-code}\nunlink_.gislock()\n```\n:::\n\n\n## Python\n\n\n::: {.cell python.reticulate='false'}\n\n```{.python .cell-code}\nsession.finish()\n```\n:::\n\n\n:::\n\n## Final remarks\n\nThe examples and comparisons presented here are intended to facilitate the\ncombination of tools and languages as well as the exchange of data and format\nconversions. We hope that's useful as a starting point for the implementation\nof different use cases and workflows that suit the needs of users.\nSee R and Python tutorials for more examples:\n\n* [GRASS and Python tutorial for beginners](../get_started/fast_track_grass_and_python.qmd)\n* [GRASS and R tutorial for beginners](../get_started/fast_track_grass_and_R.qmd)\n\n## References\n\n* [GRASS Python API docs](https://grass.osgeo.org/grass-stable/manuals/libpython/index.html)\n* [rgrass docs](https://rsbivand.github.io/rgrass/)\n\n\n***\n\n:::{.smaller}\nThe development of this tutorial was funded by the US\n[National Science Foundation (NSF)](https://www.nsf.gov/),\naward [2303651](https://www.nsf.gov/awardsearch/showAward?AWD_ID=2303651).\n:::\n", + "markdown": "---\ntitle: \"Quick comparison: R and Python GRASS interfaces\"\nauthor: \"Veronica Andreo\"\ndate: 2024-04-01\ndate-modified: today\nformat:\n html:\n toc: true\n code-tools: true\n code-copy: true\n code-fold: false\ncategories: [Python, R, intermediate]\nengine: knitr\nexecute:\n eval: false\n---\n\n\n![](images/R_Python_compare.png){.preview-image width=50%}\n\nIn this short tutorial we will highlight the similarities of R and Python GRASS interfaces\nin order to streamline the use of GRASS GIS within R and Python communities.\nAs you may know, there's\nan R package called [rgrass](https://github.com/OSGeo/rgrass/) that provides\nbasic functionality to read and write data from and into GRASS database as well\nas to execute GRASS tools in either existing or temporary GRASS projects.\nThe [GRASS Python API](https://grass.osgeo.org/grass-stable/manuals/libpython/index.html),\non the other hand, is composed of various packages that provide classes and\nfunctions for low and high level tasks, including those that can be executed\nwith rgrass.\n\n\n\nThere are some parallelisms between the\n**rgrass** and **grass.script**/**grass.jupyter** packages, i.e.,\nR and Python interfaces to GRASS GIS.\nLet's review them and go through some examples.\n\n\n| Task | rgrass function | GRASS Python API function |\n|------------------------------------------------------------|--------------------------------|---------------------------------------------------------|\n| Load library | library(rgrass) | import grass.script as gs
import grass.jupyter as gj |\n| Start GRASS and set all needed
environmental variables | initGRASS() | gs.setup.init() for scripts,
gj.init() for notebooks |\n| Execute GRASS commands | execGRASS() | gs.run_command(),
gs.read_command(),
gs.parse_command() |\n| Read raster and vector data
from GRASS | read_RAST(),
read_VECT() | gs.array.array(),
n/a |\n| Write raster and vector data
into GRASS | write_RAST(),
write_VECT() | gs.array.write(),
n/a |\n| Get raster and vector info | n/a,
vInfo() | gs.raster_info(),
gs.vector_info() |\n| Close GRASS session | unlink_.gislock() | gs.setup.finish(),
gj.finish() |\n\n: R and Python GRASS interfaces compared {.striped .hover}\n\n## Comparison examples\n\nLet's see how usage examples would look like.\n\n1. **Load the library**: We need to\nload the libraries that allow us to interface with GRASS GIS\nfunctionality and (optionally) data. For the Python case, we first need to add\nthe GRASS python package path to our system's path.\n\n::: {.panel-tabset}\n\n## R\n\n\n::: {.cell}\n\n```{.r .cell-code}\nlibrary(rgrass)\n```\n:::\n\n\n## Python\n\n\n::: {.cell python.reticulate='false'}\n\n```{.python .cell-code}\nimport sys\nimport subprocess\n\nsys.path.append(\n subprocess.check_output([\"grass\", \"--config\", \"python_path\"], text=True).strip()\n)\n\nimport grass.script as gs\nimport grass.jupyter as gj\n```\n:::\n\n\n:::\n\n2. **Start a GRASS session**: Once we loaded or imported the packages, we\nstart a GRASS session. We need to pass the path to a\ntemporary or existing GRASS project.\nIn the case of R, `initGRASS` will automatically look for GRASS binaries, alternatively we can\nspecify the path to the binaries ourselves.\nIn the case of Python, it is worth noting that while grass.script and grass.jupyter init functions\ntake the same arguments, `gj.init` also sets other environmental variables to\nstreamline work within Jupyter Notebooks, e.g., overwrite is set to true so cells\ncan be executed multiple times.\n\n::: {.panel-tabset}\n\n## R\n\n\n::: {.cell}\n\n```{.r .cell-code}\nsession <- initGRASS(gisBase = \"/usr/lib/grass84\", # where grass binaries live, `grass --config path`\n gisDbase = \"/home/user/grassdata\", # path to grass database or folder where your project lives\n location = \"nc_basic_spm_grass7\", # existing project name\n mapset = \"PERMANENT\" # mapset name\n )\n```\n:::\n\n\n## Python\n\n\n::: {.cell python.reticulate='false'}\n\n```{.python .cell-code}\n# With grass.script for scripts\nsession = gs.setup.init(path=\"/home/user/grassdata\",\n location=\"nc_basic_spm_grass7\",\n mapset=\"PERMANENT\")\n# Optionally, the path to a mapset\nsession = gs.setup.init(\"/home/user/grassdata/nc_basic_spm_grass7/PERMANENT\")\n\n# With grass.jupyter for notebooks\nsession = gj.init(path=\"/home/user/grassdata\",\n location=\"nc_basic_spm_grass7\",\n mapset=\"PERMANENT\")\n# Optionally, the path to a mapset\nsession = gj.init(\"~/grassdata/nc_basic_spm_grass7/PERMANENT\")\n```\n:::\n\n\n:::\n\n3. **Execute GRASS commands**: Both interfaces work pretty similarly, the\nfirst argument is always the GRASS tool name and then we pass the parameters\nand flags. While in R we basically use `execGRASS()` for all GRASS commands, in\nthe Python API, we have different wrappers to execute GRASS commands depending\non the nature of their output.\n\n::: {.panel-tabset}\n\n## R\n\n\n::: {.cell}\n\n```{.r .cell-code}\n# Map output\nexecGRASS(\"r.slope.aspect\",\n elevation = \"elevation\",\n slope = \"slope\",\n aspect = \"aspect\")\n\n# Text output\nexecGRASS(\"g.region\",\n raster = \"elevation\",\n flags = \"p\")\n```\n:::\n\n\n## Python\n\n\n::: {.cell python.reticulate='false'}\n\n```{.python .cell-code}\n# Map output\ngs.run_command(\"r.slope.aspect\",\n elevation=\"elevation\",\n slope=\"slope\",\n aspect=\"aspect\")\n# Text output\nprint(gs.read_command(\"g.region\",\n raster=\"elevation\",\n flags=\"p\"))\n# Text output - dictionary\nregion = gs.parse_command(\"g.region\",\n raster=\"elevation\",\n flags=\"g\")\nregion\n```\n:::\n\n\n:::\n\n4. **Read raster and vector data into other R or Python formats**:\n*rgrass* functions `read_RAST()` and `read_VECT()` convert GRASS raster and\nvector maps into terra's SpatRaster and SpatVector objects within R.\nIn the case of Python, GRASS\nraster maps that can be converted into numpy arrays through\n`gs.array.array()`. Vector attribute data can be converted into\nPandas data frames in various ways.\n\n::: {.panel-tabset}\n\n## R\n\n\n::: {.cell}\n\n```{.r .cell-code}\n# Raster\nelevr <- read_RAST(\"elevation\")\n\n# Vector\nschoolsr <- read_VECT(\"schools\")\n```\n:::\n\n\n## Python\n\n\n::: {.cell python.reticulate='false'}\n\n```{.python .cell-code}\n# Raster into numpy array\nelev = gs.array.array(\"elevation\")\n\n# Vector attributes\nimport pandas as pd\nschools = gs.parse_command(\"v.db.select\", map=\"schools\", format=\"json\")\npd.DataFrame(schools[\"records\"])\n\n# Vector geometry and attributes to GeoJSON\ngs.run_command(\"v.out.ogr\", input=\"schools\", output=\"schools.geojson\", format=\"GeoJSON\")\n```\n:::\n\n\n:::\n\n\n5. **Write R or Python objects into GRASS raster and vector maps**: R terra's\nSpatRaster and SpatVector objects can be written (back) into GRASS format with\n`write_RAST()` and `write_VECT()` functions. Within the Python environment,\nnumpy arrays can also be written (back) into GRASS raster maps with the\n`write()` method.\n\n::: {.panel-tabset}\n\n## R\n\n\n::: {.cell}\n\n```{.r .cell-code}\n# Raster\nwrite_RAST(elevr, \"elevation_r\")\n\n# Vector\nwrite_VECT(schoolsr, \"schools_r\")\n```\n:::\n\n\n## Python\n\n\n::: {.cell python.reticulate='false'}\n\n```{.python .cell-code}\n# Raster\nelev.write(mapname=\"elev_np\", overwrite=True)\n\n# GeoJSON into GRASS vector\ngs.run_command(\"v.in.ogr\", input=\"schools.geojson\", output=\"schools2\")\n```\n:::\n\n\n:::\n\n\n6. **Close GRASS GIS session**: In general, just closing R or Rstudio, as well\nas shutting down Jupyter notebook, will clean up and close the GRASS session\nproperly. Sometimes, however, especially if the user changed mapset within the\nworkflow, it is better to clean up explicitly before closing.\n\n::: {.panel-tabset}\n\n## R\n\n\n::: {.cell}\n\n```{.r .cell-code}\nunlink_.gislock()\n```\n:::\n\n\n## Python\n\n\n::: {.cell python.reticulate='false'}\n\n```{.python .cell-code}\nsession.finish()\n```\n:::\n\n\n:::\n\n## Final remarks\n\nThe examples and comparisons presented here are intended to facilitate the\ncombination of tools and languages as well as the exchange of data and format\nconversions. We hope that's useful as a starting point for the implementation\nof different use cases and workflows that suit the needs of users.\nSee R and Python tutorials for more examples:\n\n* [GRASS and Python tutorial for beginners](../get_started/fast_track_grass_and_python.qmd)\n* [GRASS and R tutorial for beginners](../get_started/fast_track_grass_and_R.qmd)\n\n## References\n\n* [GRASS Python API docs](https://grass.osgeo.org/grass-stable/manuals/libpython/index.html)\n* [rgrass docs](https://osgeo.github.io/rgrass/)\n\n\n***\n\n:::{.smaller}\nThe development of this tutorial was funded by the US\n[National Science Foundation (NSF)](https://www.nsf.gov/),\naward [2303651](https://www.nsf.gov/awardsearch/showAward?AWD_ID=2303651).\n:::\n", "supporting": [ "quick_comparison_r_vs_python_grass_interfaces_files" ], diff --git a/content/tutorials/get_started/fast_track_grass_and_R.qmd b/content/tutorials/get_started/fast_track_grass_and_R.qmd index 3cf83bb..eda45d1 100644 --- a/content/tutorials/get_started/fast_track_grass_and_R.qmd +++ b/content/tutorials/get_started/fast_track_grass_and_R.qmd @@ -18,8 +18,8 @@ execute: The [**rgrass**](https://cran.r-project.org/web/packages/rgrass/index.html) package allows us to interact with GRASS tools (and data) serving as an interface between GRASS GIS and R. -The *rgrass* package is developed and maintained by Roger Bivand and can be -found at: . In this fast track tutorial, +The *rgrass* package source code can be +found at: . In this fast track tutorial, we will learn how to use GRASS GIS from R. ::: {.callout-note title="Setup"} @@ -43,7 +43,7 @@ The main functions within **rgrass** are the following: :::{.callout-note} For further details on *rgrass* functionality, usage examples and data format -coercion, see: . +coercion, see: . ::: ## Basic usage: Choose your own adventure diff --git a/content/tutorials/r_python_interfaces_comparison/quick_comparison_r_vs_python_grass_interfaces.qmd b/content/tutorials/r_python_interfaces_comparison/quick_comparison_r_vs_python_grass_interfaces.qmd index 81b40d2..0a2b72c 100644 --- a/content/tutorials/r_python_interfaces_comparison/quick_comparison_r_vs_python_grass_interfaces.qmd +++ b/content/tutorials/r_python_interfaces_comparison/quick_comparison_r_vs_python_grass_interfaces.qmd @@ -20,7 +20,7 @@ execute: In this short tutorial we will highlight the similarities of R and Python GRASS interfaces in order to streamline the use of GRASS GIS within R and Python communities. As you may know, there's -an R package called [rgrass](https://github.com/rsbivand/rgrass/) that provides +an R package called [rgrass](https://github.com/OSGeo/rgrass/) that provides basic functionality to read and write data from and into GRASS database as well as to execute GRASS tools in either existing or temporary GRASS projects. The [GRASS Python API](https://grass.osgeo.org/grass-stable/manuals/libpython/index.html), @@ -277,7 +277,7 @@ See R and Python tutorials for more examples: ## References * [GRASS Python API docs](https://grass.osgeo.org/grass-stable/manuals/libpython/index.html) -* [rgrass docs](https://rsbivand.github.io/rgrass/) +* [rgrass docs](https://osgeo.github.io/rgrass/) ***