apply()R语言中的函数用于对数组或矩阵的元素执行数学运算。
用法: 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
相关用法
- R语言 tapply()用法及代码示例
- R语言 lapply()用法及代码示例
- R语言 rapply()用法及代码示例
- R语言 lm()用法及代码示例
- R语言 sapply()用法及代码示例
- R语言 qf()用法及代码示例
- R语言 qweibull()用法及代码示例
- R语言 qtukey()用法及代码示例
- R语言 qsignrank()用法及代码示例
- R语言 qwilcox()用法及代码示例
- R语言 qunif()用法及代码示例
- R语言 ptukey()用法及代码示例
- R语言 dsignrank()用法及代码示例
- R语言 psignrank()用法及代码示例
- R语言 dwilcox()用法及代码示例
- R语言 pwilcox()用法及代码示例
- R语言 is.matrix()用法及代码示例
- R语言 data.matrix()用法及代码示例
- R语言 as.matrix()用法及代码示例
注:本文由纯净天空筛选整理自nidhi_biet大神的英文原创作品 Perform Operations over Margins of an Array or Matrix in R Programming – apply() Function。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。
