How can I get each numeric column's mean in one data?

。_饼干妹妹 提交于 2021-02-05 10:48:05

问题


I have data named cluster_1. It has nominal variable from first column to the third.

# select the columns based on the clustering results
cluster_1 <- mat[which(groups==1),]

m_cluster_1 <-   mean(cluster_1[c(-(1:3))])

By the last statement, I can get the mean of all columns'. However, what I want is to attach the mean of each variable(column) to the bottom of the column.

How can I make it? Please let me know.


回答1:


colMeans() will give you the mean of each column in a data frame or matrix. And rbind() can be used to append the result.

rbind(cluster_1[, -(1:3)], colMeans(cluster_1[, -(1:3)]))



回答2:


A generalization of what you are doing can be found with the function addmargins. Try, for example:

cluster_1Means <- addmargins(cluster_1[, -(1:3)], margin = 1, FUN = mean)
cluster_1Means


来源:https://stackoverflow.com/questions/20194508/how-can-i-get-each-numeric-columns-mean-in-one-data

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!