【问题标题】:How to calculate centroid of group of points in R?如何计算R中点组的质心?
【发布时间】:2020-11-17 17:03:20
【问题描述】:

在 Python 中,您可以使用例如lst = [[0, 1, 2], [2, 3, 4]] 之类的列表列表。

要计算其中的质心,您可以使用以下代码:

n = len(lst[0])
centroid = [0]*n

def centroid(*args):
    for i in range(n):
        _sum = sum([element[i] for element in lst])
        centroid[i] = _sum/len(lst)
    return centroid

get_centroid(lst)

我通常如何在 R 中为一组点做同样的事情? IE。如何创建相同的功能?

【问题讨论】:

    标签: r function for-loop


    【解决方案1】:

    似乎他们将质心坐标计算为相应维度上的平均值,因此

    lst <- list(c(0, 1, 2),c(2, 3, 4))
    
    calcCentroid <- function(pointList) {
      rowMeans(do.call("cbind",pointList))
    }
    
    calcCentroid(lst)
    

    应该做的工作。 我假设您在list 中有点,并且每个点都有相同的length。 然后,您可以将它们全部组合成一个数字矩阵。它的列包含点。然后您可以执行逐行均值,在 R 中可以通过 rowMeans 完成,这是一个高度优化的函数,专门针对这项工作。

    【讨论】:

      猜你喜欢
      • 2013-09-06
      • 1970-01-01
      • 2012-04-06
      • 1970-01-01
      • 1970-01-01
      • 2016-07-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多