rfor-loopvectorraster

How can I go through all possible numbers in one loop?


I am quite new with R and trying to turn a larger SpatRaster into SpatVector. Unfortunately using vec <- as.polygons(raster) I get Error: [as.polygons] the raster is too large

So I figured I can make smaller tiles and afterwards bind the vectors together again.

my code so far looks like this (training raster is much smaller and could be polygonized without making tiles)

f <- system.file("ex/logo.tif", package = "terra")
r <- rast(f)

r_tiles <- makeTiles(r, c(34,51), filename = "training/tile_.tif") 

for(i in 1:length(r_tiles)) {                                                                           
  raster <- assign(paste0("tile_",i), rast(paste("training/tile_",i,".tif", sep = "")))                      #kleine Raster wieder einlesen
  polygon <- as.polygons(raster, aggregate = F)
  writeVector(polygon, filename = paste("training/pol_",i,".gpkg", sep = ""))
  assign(paste0("pol_",i), vect(paste("training/pol_",i,".gpkg", sep = "")))  
}

What I want to do now is bind all the smaller vectors together to again have one bigger SpatVector with the same dimensions as the original raster.

I know I could do bigPol <- rbind(pol_1, pol_2, pol_3, pol_4, pol_5, pol_6)

But is there a smoother way maybe using some sort of loop? I thought something like

for(j in 1: length(r_tiles)){bigPol <- rbind(paste0("pol_", i, sep = "")

But of course this doesn't work.


Solution

  • Following the recommendations, you can apply an r-ish function to get this job done:

    library(terra)
    
    f <- system.file("ex/logo.tif", package = "terra")
    r <- rast(f)
    
    r_tiles <- makeTiles(r, c(34,51),  filename = "training/tile_.tif")
    
    path = 'training'
    list.files(path, pattern = '.tif$', full.names = T)
    
    polygonize = function(fname, out_path){
      r = rast(fname)
      polygon = as.polygons(r, aggregate = F)
      filename = gsub('.tif','.shp',basename(fname))
      writeVector(polygon, filename = file.path(out_path, filename))
    }
    
    sapply(r_tiles, polygonize, out_path = path)
    

    Then, it's easy as loading the files in a list and then use vect again:

    vects = list.files(path, pattern = '.shp$', full.names = T)
    
    vs = lapply(vects, function(x){vect(x)})
    
    v = vect(vs)
    
    plot(v)
    

    enter image description here