In Python, you could have eg a list of lists like 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? 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
. 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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.