且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

计算R中矩阵的每列的平均值

更新时间:2023-12-01 12:45:58

您可以使用 colMeans

  ###样本数据
set.seed(1)
m< - data.frame(matrix(sample(100,20 ,replace = TRUE),ncol = 4))

###您的错误
意味着(m)
#[1] NA
#警告消息:
#在mean.default(m)中:参数不是数字或逻辑:返回NA

###使用`colMeans'
colMeans(m)
#X1 X2 X3 X4
#47.0 64.4 44.8 67.8


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) // 

I got :

  Warning message:
  In mean.default(cluster1) :
  argument is not numeric or logical: returning NA

But I can use

  mean(cluster1[[1]])

to get the mean of the first column.

How to get means for all columns ?

Any help would be appreciated.

You can use 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