计算 R 中矩阵每一列的平均值 [英] calculate the mean for each column of a matrix in R
本文介绍了计算 R 中矩阵每一列的平均值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在 R 工作室从事 R 工作.我需要计算数据框每一列的平均值.
I am working on R in R studio. I need to calculate the mean for each column of a data frame.
cluster1 // 5 by 4 data frame
mean(cluster1) //
我得到:
Warning message:
In mean.default(cluster1) :
argument is not numeric or logical: returning NA
但是我可以使用
mean(cluster1[[1]])
获取第一列的平均值.
to get the mean of the first column.
如何获得所有列的平均值?
How to get means for all columns ?
任何帮助将不胜感激.
推荐答案
你可以使用colMeans
:
### Sample data
set.seed(1)
m <- data.frame(matrix(sample(100, 20, replace = TRUE), ncol = 4))
### Your error
mean(m)
# [1] NA
# Warning message:
# In mean.default(m) : argument is not numeric or logical: returning NA
### The result using `colMeans`
colMeans(m)
# X1 X2 X3 X4
# 47.0 64.4 44.8 67.8
这篇关于计算 R 中矩阵每一列的平均值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文