R 新点最接近哪个旧点?
好, 假设我有两个点,x,y坐标R 新点最接近哪个旧点?,r,R,好, 假设我有两个点,x,y坐标 a<-c(1,1) b<-c(10,10) a您可以使用dist()计算两点之间的距离(欧几里得距离) > a <- c(1,1) > b <- c(10,10) > ce <- c(2,2) > dist(rbind(x, a)) x a 1.414214 > dist(rbind(x, b)) x b 11.31371 a is closed to ce.
a<-c(1,1)
b<-c(10,10)
a您可以使用dist()计算两点之间的距离(欧几里得距离)
> a <- c(1,1)
> b <- c(10,10)
> ce <- c(2,2)
> dist(rbind(x, a))
x
a 1.414214
> dist(rbind(x, b))
x
b 11.31371
a is closed to ce.
>a b ce dist(rbind(x,a))
x
a 1.414214
>地区(rbind(x,b))
x
b 11.31371
a不向行政长官开放。
曼尼什的答案是正确的。但是,您可能还对一个可以推广到两个以上点的解决方案感兴趣。在这种情况下,我们首先要创建一个矩阵,矩阵中的每一列都是我们的一个点。您可以随意创建此矩阵。下面是一个例子
> point_1 <- c(1, 6)
> point_2 <- c(2, 4)
> point_3 <- c(-1, -1)
> points <- matrix(c(point_1, point_2, point_3), nrow = 2)
> points
[,1] [,2] [,3]
[1,] 1 2 -1
[2,] 6 4 -1
如果在创建矩阵时使用cbind
,则每个点的名称将保留为列名。然后您可以执行距离[which.min(distance)]
并查看最近点的名称。
> point_1 <- c(1, 6)
> point_2 <- c(2, 4)
> point_3 <- c(-1, -1)
> points <- matrix(c(point_1, point_2, point_3), nrow = 2)
> points
[,1] [,2] [,3]
[1,] 1 2 -1
[2,] 6 4 -1
> my_point <- c(1, 1)
> distances <- sqrt(colSums((points - my_point) ^ 2))
> distances
[1] 5.000000 3.162278 2.828427
> closest_point <- which.min(distances)
> points[, closest_point]
[1] -1 -1
> all_points <- rbind(point_1, point_2, point_3, my_point)
> dist_mat <- dist(all_points)
> dist_mat
point_1 point_2 point_3
point_2 2.236068
point_3 7.280110 5.830952
my_point 5.000000 3.162278 2.828427