【发布时间】:2020-07-30 14:51:34
【问题描述】:
是否可以优化这段代码?
在我的数据上运行一次大约需要 2 秒,因为我必须重复运行它,这会增加整个程序的时间。
此代码设置 2(f1,f2) 地理围栏并检查 node_coords 中的点是否在这些围栏之一内。因此,它会生成一个逻辑向量索引,可用于过滤 node_coords 并仅将那些位于这两个地理围栏之一中的点留在原处。
提前非常感谢您! BR 安德烈亚斯
library("vctrs")
node_coords<-structure(list(lon = c(11.34175, 12.2063556, 12.2066937, 12.2068632,
12.2070187, 12.2078502), lat = c( 48.27649, 47.8399432, 47.8397677,
47.8396466, 47.8396952, 47.8395169)), row.names = c(172422L,
260117L, 147288L, 1337832L, 1850176L, 260151L), class = "data.frame")
check_if_point_is_within_geofence <- function(top, left, bottom, right, latitude, longitude){
# Check latitude bounds first.
if(top >= latitude && latitude >= bottom){
# If your bounding box doesn't wrap
# the date line the value
# must be between the bounds.
# If your bounding box does wrap the
# date line it only needs to be
# higher than the left bound or
# lower than the right bound.
if(left <= right && left <= longitude && longitude <= right){
return(TRUE)
} else if(left > right && (left <= longitude || longitude <= right)) {
return(TRUE)
}
}
return(FALSE)
}
geofence <- function(lon,lat){
f1 <- base::data.frame("left" = 11.34175, "bottom" = 47.98702 ,"right" = 11.77417 ,"top" = 48.27649)
f2 <- base::data.frame("left" = 12.10723, "bottom" = 47.84540, "right" = 12.15024, "top" = 47.87435 )
fences <- rbind.data.frame(f1,f2)
f_list <- apply(fences,1,function(x) check_if_point_is_within_geofence(top = x[4],left = x[1],bottom = x[2],right = x[3],latitude = lat,longitude = lon ) )
if (vec_in(TRUE,f_list))
return(TRUE)
return(FALSE)
}
index <- apply(cbind(node_coords$lon,node_coords$lat),1,function(x) geofence(x[1],x[2]) )
【问题讨论】:
-
如果您能用几句话描述您的代码,将会有所帮助。
check_if_point_is_within_geofence是描述性的命名和彻底的评论,所以很清楚。除此之外,几乎没有什么信息。你能写一两句关于geofence()、你的目标、index是什么等吗? -
您好 Gregor,感谢您的回复。我补充了几句澄清。
-
谢谢 - 更清楚了。您能否提供更好的样本数据?您提供的数据似乎返回
FALSE FALSE FALSE FALSE FALSE FALSE作为所需的结果。最好对应该产生 TRUE 和 FALSE 结果混合的数据进行测试,以确保一切正常。 -
抱歉没问题,我更改了问题中的数据集;现在应该说 TRUE FALSE FALSE FALSE FALSE FALSE