I have a raster
where the first column must be reclassified, leaving all other values as NA
. I have written the code to do this (below) but it is very inefficient as the raster size grows much beyond this toy example.
Could someone recommend a more efficient way to re-write this code so that it can handle much larger raster files? I suspect apply()
could be useful here but I'm unsure what direction to take this in.
r<-raster::raster(nrow=10, ncol=10)
r[]<-NA
for(i in 1:r@nrows){
r[(r@nrows*i)-(r@ncols-1)]<-2
}
First a better way to do what you do
library(raster)
r <- raster::raster(nrow=10, ncol=10)
for(i in 1:nrow(r)){
r[i, 1] <- 2
}
A much better alternative
r <- raster::raster(nrow=10, ncol=10)
r[,1] <- 2
But for larger rasters it is perhaps best do
r <- raster::raster(nrow=10, ncol=10)
xy <- cbind(xFromCol(r, 1), yFromRow(r, 1:nrow(r)))
r <- rasterize(xy, r, field=2)
And probably less efficient like this
r <- raster::raster(nrow=10, ncol=10)
r <- init(r, "col")
r <- reclassify(r, rbind(c(1,1,2), c(2,Inf,NA)), right=TRUE, include.lowest=TRUE)
Same idea, nicely concise
r <- subs(init(r, "col"), data.frame(from=1, to=2))