r - 如何在 R 中使用 ifelse(条件语句)覆盖两个栅格?
问题描述
我有两个栅格(图像),并希望使用以下代码覆盖它们:
# Getting the images
library(raster)
URL1 <- "https://www.dropbox.com/s/6jjz7ou1skz88wr/raster_1.tif?dl=1"
URL2 <- "https://www.dropbox.com/s/d5xuixohjqfnfze/raster_2.tif?dl=1"
download.file(URL1, destfile=paste0(getwd(),"/", "raster_1.tif"), method="auto", mode="wb", timeout="6000")
download.file(URL2, destfile=paste0(getwd(),"/", "raster_2.tif"), method="auto", mode="wb", timeout="6000")
# Reading the images
raster_1 <- raster(list.files(pattern="raster_1.tif$"))
raster_2 <- raster(list.files(pattern="raster_2.tif$"))
# Overlaying
myFun <- function(x,y){ifelse(x==0 && y==0, 0, ifelse(x==1 && y==0, 2, ifelse(x==1 && y>0, y)))}
( res <- overlay(stack(raster_1 ,raster_2), fun = Vectorize(myFun) ) )
### R gives this error
Error in .overlayList(x, fun = fun, filename = filename, forcefun = forcefun, :
cannot use this formula, probably because it is not vectorized
如果有人能帮助我,我将不胜感激。
谢谢。
解决方案
您需要一个仅使用矢量化运算符的函数。在这种情况下,布尔算术应该既成功又更有效
myFun <- function(x,y){ 0*(x==0 && y==0)+
2*(x==1 && y==0)+
y*(x==1 && y>0) }
有一些边缘情况似乎没有被覆盖。可以x
是不是正好为 0 或 1 的值吗?可以y
是消极的吗?
运行我的版本后,我得到:
> ( res <- overlay(stack(raster_1 ,raster_2), fun = Vectorize(myFun) ) )
class : RasterLayer
dimensions : 2958, 1642, 4857036 (nrow, ncol, ncell)
resolution : 500, 500 (x, y)
extent : -171063.8, 649936.2, 5317253, 6796253 (xmin, xmax, ymin, ymax)
coord. ref. : +proj=utm +zone=12 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs
data source : in memory
names : layer
values : 0, 14751 (min, max)
我认为我不需要使用Vectorize
around myFun
,enter code here
但是当我将其留在调用中时,结果似乎更有可能是正确的overlay
:
> Hmisc::describe(values(res))
values(res)
n missing distinct Info Mean Gmd .05 .10 .25
3222508 1634528 1502 0.727 4918 6403 0 0 0
.50 .75 .90 .95
0 13898 14082 14168
Value 0 13000 13200 13400 13600 13800 14000 14200 14400
Frequency 2089448 67 578 10515 69031 249817 523241 226628 46191
Proportion 0.648 0.000 0.000 0.003 0.021 0.078 0.162 0.070 0.014
Value 14600 14800
Frequency 6876 116
Proportion 0.002 0.000
当我取出 Vectorize 步骤时,我没有收到错误,但我得到了全零。
推荐阅读
- c# - 我的 DynamoDB 查询引发错误 500 无法建立连接
- javascript - 防止页面加载中的焦点/模糊事件
- python - 使用 Pandas ExcelWriter 创建的 xlsx 文件需要修复
- java - AWS EMR 如何知道所有并行步骤是否已完成
- ios - 错误:选择器“setScreenName:screenClass:”没有已知的类方法
- javascript - 滚动 Bootstrap 时更改导航栏背景
- mysql - 如何使用 bash/shell 脚本将 MySQL 查询结果输出到 Excel 中的新工作表中
- android - 离子:keycloak登录后重定向Android应用程序
- android - Flutter 中如何请求和授予通知访问、设备管理和辅助功能权限?
- vba - 无法在工作表中的相关 asins 旁边嵌入图像