Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/76.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 新点最接近哪个旧点?_R - Fatal编程技术网

R 新点最接近哪个旧点?

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.

好,

假设我有两个点,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 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