[英]How can i write equivalent R code for “ Select statement in Sas”
[英]How can I write a switch statement in R?
我无法正确编写switch语句。 并且可用的示例没有帮助。 基本上,该语句应检查单元格中的值是什么(选择:1、2、4、8、16、32、64、128),并基于该增加/减少行和列号。 某些switch语句具有2个计算。
library(raster)
fdr<-raster("fdr.tif")
row1<-50
col1<-50
cell1<-fdr[row1,col1] #The point of origin
switch (cell1,
4={row2 = row1 + 1
},
2={row2 = row1 + 1 & col2 = col1 + 1
},
1={col2 = col1 + 1
},
128={row2 = row1 - 1 & col2 = col1 + 1
},
64={row2 = row1 - 1
},
32={row2 = row1 - 1 & col2 = col1 - 1
},
16={col2 = col1 - 1
},
8={row2 = row1 + 1 & col2 = col1 - 1
}
)
除了switch语句外,我还接受其他技术。 或任何使其更快的想法。 最终,我将其包装到一个函数中,并为每个单元(像素)执行该操作。
数据:
FDR栅格(小文件): https : //www.dropbox.com/s/7o3y8w01y6zqqwm/fdr.tif?dl=0
这个概念是水流的方向: http : //courses.washington.edu/gis250/lessons/hydrology/index.html#coded
这是编写switch
并使其返回行向量col的方式:
row1 <- 50
col1 <- 50
cell1 <- 16
rowcol <- switch(as.character(cell1),
'4' = c(row1 + 1, col1),
'2' = c(row1 + 1, col1 + 1),
'1' = c(row1, col1 + 1),
'128' = c(row1 - 1, col1 + 1),
'64' = c(row1 - 1, col1),
'32' = c(row1 - 1, col1 - 1),
'16' = c(row1, col1 - 1),
'8' = c(row1 + 1, col1 - 1))
rowcol
> rowcol
[1] 50 49
您不想重复对大型栅格的每个元素进行switch
; 它将是冰河。 这是一个矢量化的操作,它从任何行/列开始,并执行一次更新/移动
## generate some dummy raster data
set.seed(1)
m <- matrix(sample(2^(0:7), 9, replace = TRUE), ncol = 3)
## collect row and column indices for raster
dd <- cbind(r = as.vector(row(m)), c = as.vector(col(m)))
## look-up matrix for row and col shifts
lu <- matrix(c( 0, 1,
1, 1,
1, 0,
1, -1,
0, -1,
-1, -1,
-1, 0,
-1, 1), ncol = 2, byrow = TRUE)
## set rownames with powers of 2 to allow indexing using `m`
rownames(lu) <- 2^(0:7)
## need `m` as a vector
mc <- as.character(as.vector(m))
## which cell to move to next given values of `m`
move <- dd + lu[mc, ]
move
这使
> move
r c
[1,] 2 1
[2,] 3 1
[3,] 3 0
[4,] 0 3
[5,] 3 3
[6,] 2 3
[7,] 0 4
[8,] 1 2
[9,] 2 2
给定输入数据,这是正确的。 现在,您面临着下一步行动并保持跟踪的问题。 在此示例中,移动会将您转移到9个像元中有3个的栅格外部像元( r
或c
为0的像元,因此,如果您索引回m
以获取移动像元中2的幂,您只会得到6个值
> m[move]
[1] 4 16 32 32 128 2
因此,您需要在行走时保持对此的跟踪,但这应该可以帮助您入门。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.