I have over 60,000 building polygons in shapefile format (polygonZ) where I need to replace the z values for all the polygon vertices. I am able to do it via a for loop but it takes a good 45 minutes to complete as it needs to iterate through all the polygons.
I was wondering if anyone has any ideas on how to speed this up?
I did try the following, thinking I could replace all the values at once via indexing but it didn’t work. I assume its due to there being a different number of vertices per polygon compared to the “new values” I want to use as replacement.
> myshape$geometry[][[1]][[1]][[1]][,2] <- new_values[]
Error in myshape$geometry[][[1]][[1]][[1]][, 2] <- new_values[] :
number of items to replace is not a multiple of replacement length
Here is a working example using stock R data.
library(sf)
library(tictoc)
# load test data
myshape <- st_read(system.file("shape/nc.shp", package = "sf"))
# make some random data
new_values <- runif(100)
# replace some values
tic()
for (row in nrow(myshape)) {
# replace
myshape$geometry[row][[1]][[1]][[1]][,2] <- new_values[row]
}
toc()