當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


R語言 apply()用法及代碼示例


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



相關用法


注:本文由純淨天空篩選整理自nidhi_biet大神的英文原創作品 Perform Operations over Margins of an Array or Matrix in R Programming – apply() Function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。