Perform Operations over Margins of an Array or Matrix in R Programming – apply() Function

apply() function in R Language is used to perform mathematical operations across elements of an array or a matrix.

Syntax: apply(x, margin, func)

Parameters:
x: Array or matrix
margin: dimension on which operation is to be applied
func: operation to be applied

Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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) 

chevron_right


Output:

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

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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) 

chevron_right


Output:

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



My Personal Notes arrow_drop_up

Recommended Posts:


Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.