R语言 对数组或矩阵的边框进行运算 – apply()函数

R语言 对数组或矩阵的边框进行运算 – apply()函数

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

语法: apply(x, margin, func)

参数:

x: 数组或矩阵

margin: 要进行运算的尺寸

func: 要进行的运算

例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) 
R

输出

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

例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) 
R

输出

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

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

登录

注册