我有一个 data.table,其中包含每个 ID、X 和 Y 坐标以及包含相邻 ID 的许多列。相邻 ID 引用此 DT 中的其他观察/行。
这里的目标是,如果某些 ID 的距离太大,则将它们设置为 NA。为此,我必须将距离函数应用于 DT 中匹配 ID 的 X 和 Y 坐标。
#the update function
update_columns <- function(dt, columns_to_update) {
for (col in columns_to_update) {
dt[, (col) := ifelse(chebyshev_distance(x,y, dt.nearest_neighbours[match.SD, c("x", "y"), on="id"]) > 10, NA, dt[[col]])]
}
return(dt.nearest_neighbours)
}
#the chebyshev distance function
chebyshev_distance <- function(x1, y1, data) {
pmax(abs(x1-data$x), abs(y1-data$y)
}
#I created a mock data.table for reproducing the problem:
dt.nearest_neighbours <- data.table(
id = c(1,2,3,4), #the ID
x = c(10, 20, 30, 40), #the X coordinate of the ID
y = c(5, 10,25,5), #the Y coordinate of the ID
V1 = c(2,3,2,1), #a neighbour of the ID -> the numbers in the V columns refer to other ID's in this dt
V2 = c(4,1,4,2), #a second neighbour of the ID
V3 = c(3,1,1,3) #third neighbour of the ID
)
当前代码出现以下错误:
'match.SD 在调用范围中找不到,它也不是列名。当 DT[...] 中的第一个参数是单个符号(例如 DT[var])时,data.table 在调用范围中查找 var'。
看来比赛没做好。我该如何解决这个问题?
通过以下代码解决了这个问题:
update_columns <- function(dt, columns_to_update) {
for (col in columns_to_update) {
dt[, (col) := ifelse(chebyshev_distance(x, y, dt[.(id = get(col)), .(id, x, y), on = "id"]) > 10, NA, dt[[col]])]
}
return(dt)
}