r - R:对靠近指定位置的单元格采样矩阵
问题描述
我正在尝试使用半随机选择方法找到收集蜗牛的网站。我在我想收集蜗牛的区域周围设置了一个 10km 2的网格,它被分成 10,000 个 10m 2的单元格。我想在 R 中随机选择这个网格来选择 200 个现场站点。
在 R 中随机采样矩阵很容易;
dat <- matrix(1:10000, nrow = 100)
sample(dat, size = 200)
但是,我想偏向采样以选择更靠近单个位置的单元格(代表更靠近研究站的站点)。用图像更容易解释这一点;
带有十字的黄色单元格代表我要采样的位置。灰色阴影是在函数中选择单元格的概率sample
,较暗的单元格更有可能被采样。
我知道我可以使用prob
in 中的参数指定采样概率sample
,但我不知道如何创建 2D 概率矩阵。任何帮助将不胜感激,我不想手动执行此操作。
解决方案
我将为 9 x 6 网格(54 个单元格)执行此操作,以便更容易查看发生了什么,并且仅对这 54 个单元格中的 5 个进行采样。您可以将其修改为 100 x 100 网格,从 10,000 个单元格中采样 200 个。
# Number of rows and columns of the grid (modify these as required)
nx <- 9 # rows
ny <- 6 # columns
# Create coordinate matrix
x <- rep(1:nx, each=ny);x
y <- rep(1:ny, nx);y
xy <- cbind(x, y); xy
# Where is the station? (edit: not snails nest)
Station <- rbind(c(x=3, y=2)) # Change as required
# Determine distance from each grid location to the station
library(SpatialTools)
D <- dist2(xy, Station)
从帮助页面dist2
dist2 采用坐标 coords1 和 coords2 的矩阵并返回坐标之间的欧几里德间距离。
我们可以使用该image
函数将其可视化。
XY <- (matrix(D, nr=nx, byrow=TRUE))
image(XY) # axes are scaled to 0-1
# Create a scaling function - scales x to lie in [0-1)
scale_prop <- function(x, m=0)
(x - min(x)) / (m + max(x) - min(x))
# Add the coordinates to the grid
text(x=scale_prop(xy[,1]), y=scale_prop(xy[,2]), labels=paste(xy[,1],xy[,2],sep=","))
较浅的色调表示距离车站较近的网格(3,2)
。
# Sampling probabilities will be proportional to the distance from the station, which are scaled to lie between [0 - 1). We don't want a 1 for the maximum distance (m=1).
prob <- 1 - scale_prop(D, m=1); range (prob)
# Sample from the grid using given probabilities
sam <- sample(1:nrow(xy), size = 5, prob=prob) # Change size as required.
xy[sam,] # Thse are your (**MY!**) 5 samples
x y
[1,] 4 4
[2,] 7 1
[3,] 3 2
[4,] 5 1
[5,] 5 3
要确认样本概率是否正确,您可以模拟许多样本并查看哪些坐标被采样最多。
snail.sam <- function(nsamples) {
sam <- sample(1:nrow(xy), size = nsamples, prob=prob)
apply(xy[sam,], 1, function(x) paste(x[1], x[2], sep=","))
}
SAMPLES <- replicate(10000, snail.sam(5))
tab <- table(SAMPLES)
cols <- colorRampPalette(c("lightblue", "darkblue"))(max(tab))
barplot(table(SAMPLES), horiz=TRUE, las=1, cex.names=0.5,
col=cols[tab])
如果使用 100 x 100 网格并且站点位于坐标 (60,70),则图像将如下所示,采样网格显示为黑点:
这些点倾向于靠近台站,尽管采样的可变性可能使这一点难以看到。如果你想给车站附近的网格更多的权重,那么你可以重新调整概率,我认为可以这样做,以节省旅行成本,但在估计数量时需要将这些权重纳入分析整个地区的蜗牛。在这里,我对概率进行了立方计算,以便您可以看到会发生什么。
sam <- sample(1:nrow(xy), size = 200, prob=prob^3)
点位于车站附近的趋势现在更加明显。