我需要确定位于给定矩形内的一组 xy 坐标的分数。该矩形定义为边距坐标系边缘给定距离的区域(在这种情况下,坐标系的边界大致为 (-50, -20), (-50, 20), (50, 20 ), (50, -20)。另外,我希望能够在距边缘不同距离的矩形上测试结果。我的方法如下:
# set initial limits to the coordinate system
lim.xleft = -50
lim.xright = 50
lim.ybottom = -20
lim.ytop = 20
frac.near.edge <- function(coord.pairs, tolerance){
# set the coordinates of the rectangle of interest
exclude.xleft = lim.xleft + tolerance
exclude.xright = lim.xright - tolerance
exclude.ybottom = lim.ybottom + tolerance
exclude.ytop = lim.ytop - tolerance
out <- vector()
# loop through the pairs testing whether the point is inside the rectangle or outside
for(i in 1:nrow(coord.pairs)){
if(coord.pairs[i, 1] > exclude.xleft & coord.pairs[i, 1] < exclude.xright & coord.pairs[i, 2] > exclude.ybottom & coord.pairs[i, 2] < exclude.ytop){
out[i] <- "in"
} else {
out[i] <- "out"
}
}
# return how many points were inside the rectangle and how many were outside
return(table(out))
}
# try it out on something much bigger!
foo <- data.fram(x = runif(100), y = runif(100))
system.time(frac.near.edge(foo, tolerance = 5))
这对于大型数据集来说非常慢(我的数据集包含大约 10^5 xy 对)。我怎样才能加快速度?绕过循环的方法?