问题
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