rspatial / terra

R package for spatial data handling https://rspatial.github.io/terra/reference/terra-package.html
GNU General Public License v3.0
534 stars 88 forks source link

Error: std::bad_alloc when using rasterize with by #1581

Open salvatorev89 opened 1 month ago

salvatorev89 commented 1 month ago

I got an Error: std::bad_alloc using the rasterize(..., by=...) function after updating my R system. I got to fix the error by installing the terra package 1.7.65. Is there something to be fixed?

rhijmans commented 1 month ago

Perhaps, but you are not providing sufficient information. I would need specifics about your precise call of that method and the data used.

salvatorev89 commented 1 month ago

This is the loop that gave me problem after updating the package:

sp.list <- unique(new_AB$SPECIE)
empty.r <- rast(xmin=min(new_AB$new_longitude)-res.grid, xmax=max(new_AB$new_longitude)+res.grid, ymin=min(new_AB$new_latitude)-res.grid, ymax=max(new_AB$new_latitude)+res.grid,
                crs = "EPSG:4326", res = res.grid)
list.r <- list()
years <- 1994:2021
for (i in 1:length(years)) {
  sub.y <- subset(new_AB, year == years[i], select = c("new_longitude","new_latitude","SPECIE","KG_KM"))
  if (length(unique(sub.y$SPECIE)) < length(sp.list)) {
    fill.y <- data.frame(new_longitude = sub.y$new_longitude[1], new_latitude = sub.y$new_latitude[1],
                         SPECIE = sp.list[!(sp.list %in% sub.y$SPECIE)], KG_KM = 0)
    sub.y <- rbind(sub.y, fill.y)
  }
  point.vect <- vect(sub.y, geom=c("new_longitude","new_latitude"), crs="EPSG:4326")
  rasterized.points <- rasterize(point.vect, empty.r, field = "KG_KM", fun = mean, by="SPECIE")
  names(rasterized.points) <- sort(unique(sub.y$SPECIE))
  p <- as.data.frame(rasterized.points, xy=T)
  p[is.na(p)] <- 0
  p$year <- years[i]
  list.r[[i]] <- p
  print(paste0("Year processed ",years[i]))
}

As already said, no problem at all, after rolling back to version 1.7.65.