简体   繁体   English

如何计算R中点组的质心?

[英]How to calculate centroid of group of points in R?

In Python, you could have eg a list of lists like lst = [[0, 1, 2], [2, 3, 4]] .在 Python 中,你可以有一个像lst = [[0, 1, 2], [2, 3, 4]]

To calculate the centroid in this, you could have the following code:要在此计算质心,您可以使用以下代码:

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)

How can I do the same thing in R for a group of points generally?通常如何在 R 中为一组点做同样的事情? Ie how can the same function be created?即如何创建相同的功能?

It seems like they calculate the centroid coordinate-wise as the mean over the corresponding dimension, hence似乎他们将质心坐标计算为相应维度上的平均值,因此

lst <- list(c(0, 1, 2),c(2, 3, 4))

calcCentroid <- function(pointList) {
  rowMeans(do.call("cbind",pointList))
}

calcCentroid(lst)

should do the work.应该做的工作。 I assume you have the points in a list and every point has the same length .我假设你有一个list的点,每个点都有相同的length Then, you can combine them all together to a numeric matrix.然后,您可以将它们全部组合成一个数字矩阵。 Its columns contain the points.它的列包含点。 Then you can perform a rowwise mean, which in R can be done via rowMeans , which is a highly optimized function just for this job.然后你可以执行一个 rowwise mean,这在R可以通过rowMeans来完成,这是一个高度优化的函数,专门用于这项工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM