<p><strong>数据准备</strong></p>
<pre><code># Load packages
library(raster)
## Create example raster layer
# create an empty raster layer
r <- raster(ncol = 10, nrow = 10)
# assign values to cells
values(r) <- 1:ncell(r)
# Inspect the raster layer
plot(r)
</code></pre>
<p><strong>解决方案1</strong>:此解决方案使用<code>raster</code>和<code>dplyr</code>包中的函数。在</p>
^{pr2}$
<p><strong>解决方案2</strong>:这只使用<code>raster</code>包</p>
<pre><code># Initialize an empty list to store the results of each row
raster_list <- list()
# A for loop to crop the image and assign 0 or 1 to see if it is the maximum of that row
for (i in 1:nrow(r)){
# Get the extent of each row
temp_ext <- extent(r, r1 = i, r2 = i, c1 = 1, c2 = ncol(r))
# Crop the raster for only one row
temp_r <- crop(r, temp_ext)
# Get the maximum of one row
temp_max <- max(values(temp_r), na.rm = TRUE)
# Use raster algebra
temp_r[temp_r != temp_max] <- 0
temp_r[temp_r == temp_max] <- 1
# Save the results to the raster_list
raster_list <- c(raster_list, temp_r)
}
# Merge all rasters
m <- do.call(merge, raster_list)
# Examine the result
plot(m)
</code></pre>