我已经尝试解决这个问题好几天了。最初我有树的位置数据相对于一个中心(角度到北方和中心和距离)。我已经计算了每棵树的坐标,以获得它们在空间中的位置。
然后我必须找到不同树之间的最小距离,并记下最近的树和它的距离。
我开始用双循环推理,但我总是只得到表的最后一行的结果。我终于算出了树I和它的第一个邻居之间的最小距离。但是我找不到最近的树对应的数字。例如:树1与树2、3、4、5、6相邻;距离是最小的树1和3之间,我希望我的代码返回数字3为I = 1(树数1)。这是我的代码,希望我的解释足够清楚,你可以帮助我非常感谢
用www.DeepL.com/Translator(免费版)翻译
代码:
SM = data_RSD %>% mutate(Xc= Dist*sin(Angle*(pi/200)), Yc= Dist *cos(Angle*(pi/200)))
SM$Dist_min=0
SM$Nb_tree_min=0
for(i in 1:dim(SM)[1]){
x<-sqrt((SM$Xc[1:dim(SM)[1]]-SM$Xc[i])^2+(SM$Yc[1:dim(SM)[1]]-SM$Yc[i])^2) #distance
SM$Dist_min[i]= (min(x[x > 0]))
SM$Nb_tree_min[i]= SM$Number[(min(x[x > 0]))]
i<-i+1
}
一种方法(不依赖于专用的空间库),根据您的数据结构进行调整:
create example dataframedf:
library(dplyr) ## for dataframe manipulations later on
set.seed(4711) ## ensure same random values for reproduction
df <- data.frame(id = letters[1:5],
x = runif(5),
y = runif(5),
)
## > df
##
## id x y
## 1 a 0.9656003 0.61809459
## 2 b 0.5606107 0.34204836
## 3 c 0.9147251 0.16194603
## 4 d 0.1829564 0.27060681
## 5 e 0.8842138 0.07892783
生成距离矩阵:
distance_matrix <- df %>%
select(x, y) %>%
dist(.) %>% ## calculate distances
as.matrix %>% ## convert it to matrix
`+`(., diag(NA, dim(.))) ## see 1)
## 1) a shorthand for replacing the diagonal (distances of points to
## themselves) with NAs so that points are not returned as their own
## nearest neighbours
从距离矩阵中识别ID和到最近邻居的距离:
df %>%
rowwise %>%
mutate(
neighbour_distances = list(distance_matrix[id,]), ## see 2)
nearest_neighbour = which.min(neighbour_distances) %>% names,
distance = neighbour_distances[nearest_neighbour]
)
## 2) you can store not only single values but vectors and many object
## classes (e.g. models) in a column by wrapping them in a list
输出:
## # A tibble: 5 x 6
## # Rowwise:
## id x y neighbour_distances nearest_neighbour distance
## <chr> <dbl> <dbl> <list> <chr> <dbl>
## 1 a 0.966 0.618 <dbl [5]> c 0.459
## 2 b 0.561 0.342 <dbl [5]> d 0.384
## 3 c 0.915 0.162 <dbl [5]> e 0.0884
## 4 d 0.183 0.271 <dbl [5]> b 0.384
## 5 e 0.884 0.0789 <dbl [5]> c 0.0884
结果的快速视觉合理性检查:
df %>%
ggplot() + geom_text(aes(x, y, label = id)) +
coord_fixed()