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:
A = matrix( 1 : 9 , 3 , 3 )
print (A)
r = apply (A, 1 , sum )
print (r)
c = apply (A, 2 , sum )
print (c)
|
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:
A = matrix( 1 : 9 , 3 , 3 )
print (A)
r = apply (A, 1 , prod)
print (r)
c = apply (A, 2 , prod)
print (c)
|
Output:
[, 1] [, 2] [, 3]
[1, ] 1 4 7
[2, ] 2 5 8
[3, ] 3 6 9
[1] 28 80 162
[1] 6 120 504
Last Updated :
04 Jun, 2020
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...