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)
输出
[, 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