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

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

Output:

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

Example 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)  `

Output:

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

My Personal Notes arrow_drop_up 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.

Article Tags :

1

Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.