R 語言中的 colSums() 函數用於計算矩陣或數組列的總和。
用法: colSums (x, na.rm = FALSE, dims = 1)
參數:
x:矩陣或數組
dims:這是一個整數值,其維度被視為 ‘columns’ 求和。它超過尺寸 1:dims。
範例1:
# R program to illustrate
# colSums function
  
# Initializing a matrix with 3 
# rows and 3 columns
x <- matrix(rep(1:9), 3, 3)
  
# Getting the matrix representation
x
  
# Calling the colSums() function
colSums(x)輸出:
     [, 1] [, 2] [, 3]
[1, ]    1    4    7
[2, ]    2    5    8
[3, ]    3    6    9
[1]  6 15 24
範例2:
# R program to illustrate
# colSums function
  
# Initializing a 3D array
x <- array(1:12, c(2, 3, 3))
  
# Getting the array representation
x
  
# Calling the colSums() function
colSums(x, dims = 1)
colSums(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, ]    3   15    3
[2, ]    7   19    7
[3, ]   11   23   11
[1] 21 57 21
相關用法
- R語言 colMeans()用法及代碼示例
- R語言 col()用法及代碼示例
- R語言 scale()用法及代碼示例
- R語言 tr()用法及代碼示例
- R語言 cumsum()用法及代碼示例
- R語言 ncol()用法及代碼示例
- R語言 merge()用法及代碼示例
- R語言 rename()用法及代碼示例
- R語言 select()用法及代碼示例
- R語言 is.matrix()用法及代碼示例
- R語言 data.matrix()用法及代碼示例
- R語言 as.matrix()用法及代碼示例
- R語言 acos()用法及代碼示例
- R語言 cos()用法及代碼示例
注:本文由純淨天空篩選整理自Kanchan_Ray大神的英文原創作品 Calculate the Sum of Matrix or Array columns in R Programming – colSums() Function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。
