Rasterize multiple columns of a sf object: for loop and map function

Hi,
I have a spatial data frame (sf object 280 columns) with 279 variables (columns) plus 1 geometry column,
I am interested in creating 275 rasters (I'd like to skip 4 columns) based on the values stored from column "v1" to "v275 " (the name of my columns are indeed v1,v2,v3 etc )
I have tried to use a for loop but the R session aborts every time I run the loop ..
I have also tried to use the map function from purrr package but I did not succeed ..
I'd really appreciate any advice !!

class(shape_predictions)
[1] "sf" "data.frame"

This is my code

variables<-c(paste("v",1:275, sep = "")) # create a vector containing the variables names to loop over 
raster_grid<- rast("data/raster_grid.tif")    # import the raster grid used as reference  
s <- list()

for (i in variables){
  s[[i]] <- rasterize(shape_predictions, raster_grid, shape_predictions[[i]])
}
sr <- stack(s)

With that naming scheme of a sf frame dat and assuming that the geometry column is last, I'd start with

idx <-  1:length(dat)
idx <-  idx[-length[dat])
idx <- idx[-c(34:37)] # example of four columns to skip

then write and test

x <- 1
f <- function (x) rasterize(dat, raster_grid, dat[[x]])
f(1)
rm(x)

Preallocate a receiver object to be identified to stack(). Here I will assume the transformed variables can be conveniently extracted from a list object since without a reprex. See the FAQ I'm to lazy to reverse engineer the problem.

recv <- vector(length = length(idx)

(The default type created this way is a list. Go figure.)

Then, untested by me, this should create your list with a for loop

for(i in seq_along(idx)) recv[i] = f(i)

or maybe

o <- lapply(dat[idx],f)

The purrr flavors I've always found unintuitive, despite their intention to be easier to grasp, and as I got over my discomfort with punctuation/positional syntax in {base}, I've come to prefer it as less syntax-intensive than the tidyverse way.

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.