📜  在 R 编程中计算矩阵或数组列的总和 - colSums()函数

📅  最后修改于: 2022-05-13 01:54:21.889000             🧑  作者: Mango

在 R 编程中计算矩阵或数组列的总和 - colSums()函数

R 语言中的colSums()函数用于计算矩阵或数组列的总和。

示例 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