gpt4 book ai didi

r - 使用条件循环遍历 data.table 行

转载 作者:行者123 更新时间:2023-12-02 04:24:46 31 4
gpt4 key购买 nike

我有一个包含 ID 和位置的 data.table。例如,这里有一行:(它有 col 和 row 名称,不知道是否重要)

locations<-data.table(c(11,12),c(-159.58,0.2),c(21.901,22.221))
colnames(locations)<-c("id","location_lon","location_lat")
rownames(locations)<-c("1","2")

然后我想遍历这些行并将它们与另一个点(使用纬度、经度)进行比较。在 for 循环中它起作用:

for (i in 1:nrow(locations)) {
loc <- locations[i,]
dist <- gdist(-159.5801, 21.901, loc$location_lon, loc$location_lat, units="m")
if(dist <= 50) {
return (loc)
}
return (NULL)
}

并返回:

id location_lon location_lat

1: 11 -159.58 21.901

但我想使用申请。以下代码无法运行:

dists <- apply(locations,1,function(x) if (50 - gdist(-159.5801, 21.901, x$location_lon, x$location_lat, units="m")>=0) x else NULL)

$ operator is invalid for atomic vectors 错误。更改为按位置引用 (x[2],x[3]) 不足以解决此问题,我明白了

Error in if (radius - gdist(lon, lat, x[2], x[3], units = "m") >= 0) x else NULL : 
missing value where TRUE/FALSE needed

这是因为data.table被转成了矩阵,坐标被当成了文本而不是数字。有没有办法克服这个问题?该解决方案需要高效(我想对 >1,000,000 个不同的坐标运行此检查)。如果需要,可以更改位置表的数据结构。

最佳答案

不需要循环,只需按预期使用data.table。如果您只想查看距所需位置 50 米范围内的行,则只需

locations[, if (gdist(-159.58, 21.901, location_lon, location_lat, units="m") <= 50) .SD, id]
## id location_lon location_lat
## 1: 11 -159.58 21.901

在这里,我们通过 locations 数据集本身中的 id 列进行迭代,并检查每个 id 是否在距离 50 米以内>-159.58, 21.901。如果是这样,我们将调用 .SD,它基本上是特定 id 的数据集本身。


作为旁注,data.table 没有row.names,因此无需指定它们,参见here , 例如

关于r - 使用条件循环遍历 data.table 行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27836507/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com