Related Articles
Perform Operations over Margins of an Array or Matrix in R Programming – apply() Function
• Last Updated : 04 Jun, 2020

`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
Recommended Articles
Page :