R 語言中的 colMeans() 函數用於計算矩陣或數組的每一列的均值。
用法: colMeans(x, dims = 1)
參數:
x:二維或更多維度的數組,包含數值、複數、整數或邏輯值,或數值 DataFrame 
dims:整數值,將哪些維度視為 ‘columns’ 求和。它超過尺寸 1:dims。
範例1:
# R program to illustrate
# colMeans function
  
# Initializing a matrix with
# 3 rows and 3 columns
x <- matrix(rep(1:9), 3, 3)
  
# Getting matrix representation
x
  
# Calling the colMeans() function
colMeans(x)輸出:
     [, 1] [, 2] [, 3]
[1, ]    1    4    7
[2, ]    2    5    8
[3, ]    3    6    9
[1] 2 5 8
範例2:
# R program to illustrate
# colMeans function
  
# Initializing a 3D array
x <- array(1:12, c(2, 3, 3))
  
# Getting the array representation
x
  
# Calling the colMeans() function
  
# for dims = 1, x[, 1, 1], x[, 2, 1], x[, 3, 1],
# x[, 1, 2] ... are columns
colMeans(x, dims = 1)
  
# for dims = 2, x[,,1], x[,,2], x[,,3]
# are columns
colMeans(x, dims = 2)輸出:
,, 1
     [, 1] [, 2] [, 3]
[1, ]    1    3    5
[2, ]    2    4    6,, 2
     [, 1] [, 2] [, 3]
[1, ]    7    9   11
[2, ]    8   10   12,, 3
     [, 1] [, 2] [, 3]
[1, ]    1    3    5
[2, ]    2    4    6
     [, 1] [, 2] [, 3]
[1, ]  1.5  7.5  1.5
[2, ]  3.5  9.5  3.5
[3, ]  5.5 11.5  5.5
[1] 3.5 9.5 3.5
相關用法
- R語言 mean()用法及代碼示例
- R語言 weighted.mean()用法及代碼示例
- R語言 rowMeans()用法及代碼示例
- R語言 colSums()用法及代碼示例
- R語言 tr()用法及代碼示例
- R語言 max.col()用法及代碼示例
- R語言 is.matrix()用法及代碼示例
- R語言 data.matrix()用法及代碼示例
- R語言 as.matrix()用法及代碼示例
- R語言 acos()用法及代碼示例
- R語言 cos()用法及代碼示例
- R語言 cosh()用法及代碼示例
- R語言 sin()用法及代碼示例
- R語言 sinh()用法及代碼示例
注:本文由純淨天空篩選整理自Kanchan_Ray大神的英文原創作品 Calculate the Mean of each Column of a Matrix or Array in R Programming – colMeans() Function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。
