使用条件循环 data.table 行
Loop over a data.table rows with condition
我有一个 data.table 保存 ID 和位置。例如,这里有一行:
(它有列名和行名,不知道是否重要)
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 个不同的坐标运行此检查)。如果需要,可以更改位置 table 的数据结构。
不需要循环,只需按预期使用 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
是否在距 -159.58, 21.901
50 米以内。如果是这样,我们将调用 .SD
,这基本上是特定 id
.
的数据集本身
附带说明,data.table
没有 row.names
,因此无需指定它们,参见 here,例如
我有一个 data.table 保存 ID 和位置。例如,这里有一行: (它有列名和行名,不知道是否重要)
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 个不同的坐标运行此检查)。如果需要,可以更改位置 table 的数据结构。
不需要循环,只需按预期使用 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
是否在距 -159.58, 21.901
50 米以内。如果是这样,我们将调用 .SD
,这基本上是特定 id
.
附带说明,data.table
没有 row.names
,因此无需指定它们,参见 here,例如