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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。
