Reputation: 1
I am trying to take all cell values >=1 from a RasterStack and apply them to a new, blank raster. I am unsure whether to try this through a for loop or if there is a way to do this via simple raster calculations. So far, I have the following:
dir <- "C://Users//path"
files<- list.files(path = dir,
full.names = TRUE, pattern = ".tif$")
raster_stack <- stack(files)
s <- subset(raster_stack, 38:48)
From here, I am unsure how to proceed. Any insight would be greatly appreciated. Thank you in advance.
Upvotes: 0
Views: 490
Reputation: 47091
With these example data
library(terra)
s <- rast(system.file("ex/logo.tif", package="terra"))
s <- round(s/100)
(it is not clear what you want for the cells that are < 1, "blank" has no meaning, but you probably want NA
or 0
)
You can do this to get a TRUE / FALSE raster (where TRUE is equivalent to 1 and FALSE is equivalent to 0)
x <- s >= 1
plot(x)
or this to get a value (1 in this case) / NA raster
y <- ifel(s >= 1, 1, NA)
You can also use classify
for that (it is more efficient)
m <- matrix(c(-Inf, 1, NA,
1, Inf, 1), ncol=3, byrow=TRUE)
z <- classify(s, m, right=FALSE)
Upvotes: 0
Reputation: 3604
library(raster)
#> Loading required package: sp
x1 <- raster(ncol=10, nrow=10, xmn=-10, xmx=10, ymn=-10, ymx=10)
x2 <- raster(ncol=10, nrow=10, xmn=-10, xmx=10, ymn=-10, ymx=10)
x1[,c(1,5,9)] <- 1
x2[c(1,5,9),] <- 1
plot(x1)
plot(x2)
s <- stack(c(x1, x2))
t <- sum(s)
plot(t)
If you wish to add particular layers, then:
t <- s$layer.1 + s$layer.2
Created on 2022-01-25 by the reprex package (v2.0.1)
Upvotes: 0