gpt4 book ai didi

r - R中两个3D点之间的距离

转载 作者:行者123 更新时间:2023-12-02 00:28:06 25 4
gpt4 key购买 nike

我有两个 2 点 A(x,y,z) e B(x1,y1,z1)。我想计算时间 1、时间 2、时间 3 这些点之间的欧氏距离。

所以,我有这样一个矩阵:

         x     y     z     x1     y1     z1    distance
time1 2 1 2 4 6 8 ?
time2 3 4 3 6 6 7 ?
time3 6 8 9 4 3 3 ?

正如您在上面看到的,我想添加一个列(距离),其中我报告 A e B 之间的欧氏距离。

你有什么建议吗?

最佳答案

您正在寻找 dist() 函数:

df <- read.table(header = TRUE, text = "
x y z x1 y1 z1
time1 2 1 2 4 6 8
time2 3 4 3 6 6 7
time3 6 8 9 4 3 3")

df$distance <- apply(df, 1, function(x) dist(matrix(x, nrow = 2, byrow = TRUE)))

df
#> x y z x1 y1 z1 distance
#> time1 2 1 2 4 6 8 8.062258
#> time2 3 4 3 6 6 7 5.385165
#> time3 6 8 9 4 3 3 8.062258

来自 help("dist"):

Description

This function computes and returns the distance matrix computed by using the specified distance measure to compute the distances between the rows of a data matrix.

Usage

dist(x, method = "euclidean", diag = FALSE, upper = FALSE, p = 2)

所以,如果你给它一个 m 矩阵,比如

2 1 2
4 6 8

distance(m) 将计算 c(2, 1, 2)c(4, 6, 8) 之间的欧氏距离>。然后我们可以将 dist() 函数应用于数据集的每一行,该函数调用从该行构造的矩阵,其中新矩阵的第一行是 xyz 数据集那一行的观察值,新矩阵的第二行是 x1y1 ,以及数据集中该行的 z1 观察值。

关于r - R中两个3D点之间的距离,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52966981/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com