R - Apply Function to each Element of a Matrix - Tutorial Kart

R ? Apply Function to each Element of a Matrix

R ? Apply Function to each Element of a Matrix

We can apply a function to each element of a Matrix, or only to specific dimensions, using apply().

Syntax of apply()

apply(X, MARGIN, FUN, ...)

apply(X, MARGIN, FUN, ...)

where

X an array or a matrix MARGIN is a vector giving the subscripts which the function will be applied over. For a matrix 1 indicates rows, 2 indicates columns, c(1,2) indicates rows and columns. If X has named dimension names, it can be a character vector selecting dimension names. FUN is the function to be applied on the element(s) of x

Apply Function on each Element of a Matrix

In this example, we will take a 2D matrix. Write a function to increment the argument by 2. Then apply the function on all elements of the matrix.

applyExample.r

M = matrix(c(1:12), nc ol=3) incrementBy2 print(M) [,1] [,2] [,3]

[1,] 1 5 9 [2,] 2 6 10 [3,] 3 7 11 [4,] 4 8 12 > print(y)

[,1] [,2] [,3] [1,] 3 7 11 [2,] 4 8 12 [3,] 5 9 13 [4,] 6 10 14

Apply Function on each Element of a Matrix ? Pass Additional Arguments to the Function

You can also pass additional arguments to the function. Provide the additional arguments to the function as parameters to apply() after the function argument.

In this example, we will pass an argument n to the function applied on each element of the matrix.

applyExample.r

M = matrix(c(1:12), nc ol=3)

incrementByN print(y)

[,1] [,2] [,3] [1,] 7 11 15 [2,] 8 12 16 [3,] 9 13 17 [4,] 10 14 18

> print(M) [,1] [,2] [,3]

[1,] 1 5 9 [2,] 2 6 10 [3,] 3 7 11 [4,] 4 8 12 > print(y)

[,1] [,2] [,3] [1,] 7 11 15 [2,] 8 12 16 [3,] 9 13 17 [4,] 10 14 18

Conclusion

In this R Tutorial, we learned how to apply a function on each element of a matrix using apply() .

Home - Get Started

R Tutorial R Script File R Working Directory R Data Types R Variables R Operators R Vectors R Matrix

Decision Making

R Decision Making R if R if..else R if..else if...else R switch

Loops

R Loops R repeat loop R while loop R for loop

R break

Strings

R Strings Find length of String in R Extract Substring from a String in R Concatenate two or more Strings in R

Functions

R Functions

DataFrame

R Data Frame Sort R Data Frame by Column For each row in an R Data Frame Import Excel Data into R Dataframe Convert R Dataframe to Matrix R Dataframe - Delete Rows R Dataframe - Drop Columns R Dataframe - Add Column R Dataframe - Change Column Name R Dataframe - Remove Duplicate Rows R Dataframe - Replace NA with 0 Convert Matrix to R Dataframe

Handling Data from Files

R CSV Files - Read, Filter, Write R Read Excel XLS XLSX files

Charts & Graphs

R Pie Charts R Line Graphs

Statistical Analysis

R Mean of a Vector R Median of a Vector

................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download