當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


R語言 colSums()用法及代碼示例


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

相關用法


注:本文由純淨天空篩選整理自Kanchan_Ray大神的英文原創作品 Calculate the Sum of Matrix or Array columns in R Programming – colSums() Function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。