Running grass commands within R is easy using either the system function or the spgrass6 package. But sometimes the GRASS outputs are not easy to read into a data frame or vector. For example, what if you want a vector with all raster data layers in mapset ‘species’.
EDIT: There is a much easier solution, see my next post. Read on if you want to see a much more cumbersome solution using gsub and strsplit to convert the output in a vector.
In GRASS you would use the function
g.list type=rast mapset=species
The output is not very easy to handle though, it looks e.g., like:
---------------------------------------------- raster files available in mapset <species>: Acacia_seyal Warburgia_ugandensisv2 Acacia_seyalv2 Zanthoxylum_chalybeum Albizia_gummifera Zanthoxylum_chalybeumv2 ---------------------------------------------- (Tue Feb 22 23:15:17 2011) Command finished (0 sec)
In R (which should be run within GRASS), you can run one of the two lines below:
system("g.list type=rast mapset=species", intern=TRUE)
execGRASS("g.list", parameters=list(type="rast", mapset="species"), intern=TRUE)
However, the output is not easy to use in R without some further processing:
[1] "----------------------------------------------" [2] "raster files available in mapset <species>:" [3] "Acacia_seyal Warburgia_ugandensisv2" [4] "Acacia_seyalv2 Zanthoxylum_chalybeum" [5] "Albizia_gummifera Zanthoxylum_chalybeumv2" [6] "" [7] "----------------------------------------------"
The first and last two rows are easy to remove:
a <- execGRASS("g.list", parameters=list(type="rast", mapset="species"), intern=TRUE)
a <- a[-c(1,2,length(a)-1,length(a))]
The next two lines of code will replace the white spaces by a comma, split the vector elements using the comma as separator and combine all in one vector:
b <- as.vector(gsub('[[:space:]]+', ',', a))
c <- unlist(strsplit(b,","))
There you go, a nice vector with one layer name per vector element.
Thinks are getting a little bit more complicated if you want to list raster and vector layers or layers from more than one mapset. But that is for later.

Pingback: Using the GRASS command g.mlist in R | Ecostudies