📜  在 R 编程中对数组或矩阵的边距执行操作 – apply()函数

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

在 R 编程中对数组或矩阵的边距执行操作 – apply()函数

R 语言中的apply()函数用于对数组或矩阵的元素执行数学运算。

示例 1:

# R program to illustrate 
# apply() function 
    
# Creating a matrix 
A = matrix(1:9, 3, 3) 
print(A) 
    
# Applying apply() over row of matrix 
# Here margin 1 is for row  
r = apply(A, 1, sum) 
print(r) 
    
# Applying apply() over column of matrix 
# Here margin 2 is for column 
c = apply(A, 2, sum) 
print(c) 

输出:

[, 1] [, 2] [, 3]
[1, ]    1    4    7
[2, ]    2    5    8
[3, ]    3    6    9
[1] 12 15 18
[1]  6 15 24

示例 2:

# R program to illustrate 
# apply() function 
    
# Creating a matrix 
A = matrix(1:9, 3, 3) 
print(A) 
    
# Applying apply() over row of matrix 
# Here margin 1 is for row  
r = apply(A, 1, prod) 
print(r) 
    
# Applying apply() over column of matrix 
# Here margin 2 is for column 
c = apply(A, 2, prod) 
print(c) 

输出:

[, 1] [, 2] [, 3]
[1, ]    1    4    7
[2, ]    2    5    8
[3, ]    3    6    9
[1]  28  80 162
[1]   6 120 504