Outer() Function in R Programming Example
Example 1: Outer Product of Two Vector
R
# R program to illustrate # outer function # Initializing two arrays of elements x <- c (1, 2, 3, 4, 5) y<- c (2, 4, 6) # Multiplying array x elements with array y elements # Here multiply (*) parameter is not used still this # function take it as default outer (x, y) |
Output:
[, 1] [, 2] [, 3] [1, ] 2 4 6 [2, ] 4 8 12 [3, ] 6 12 18 [4, ] 8 16 24 [5, ] 10 20 30
Example 2: outer Function for Vector and Single Value
R
# R program to illustrate # outer function # Initializing two arrays of elements x <- 1:8 y<- 4 # Multiplying array x elements with array y elements # Here multiply (*) parameter is not used still this # function take it as default outer (x, y, "+" ) |
Output:
[,1] [1,] 5 [2,] 6 [3,] 7 [4,] 8 [5,] 9 [6,] 10 [7,] 11 [8,] 12
Types of outer() Functions:
Since the outer() method is general, you can create your own unique functions and utilize them in conjunction with outer(). The following are a few of the more typical outer() function types:
1. Arithmetic Functions: The most typical application of outer() involves adding and subtracting two vectors. The arithmetic operations +, -, *, /,, %%, and %/% can all be used using outer().
As an illustration, suppose we want to determine the sum of each pair of elements in the two vectors x and y:
R
x <- 1:3 y <- 4:6 outer (x, y, FUN = "+" ) |
Output:
[,1] [,2] [,3] [1,] 5 6 7 [2,] 6 7 8 [3,] 7 8 9
2. Statistical Functions: Statistical operations can also be applied to two vectors using the outer() method. For illustration, suppose we want to determine the correlation between the two vectors x and y:
R
# Creating two matrices X <- matrix (1:6, nrow = 2, ncol = 3) Y <- matrix (1:4, nrow = 2, ncol = 2) # Trying to multiply the two matrices using the outer function outer (X, Y, "*" ) |
Output:
[,1] [,2] [,3] [1,] 1 3 5 [2,] 2 4 6 , , 2, 1 [,1] [,2] [,3] [1,] 2 6 10 [2,] 4 8 12 , , 1, 2 [,1] [,2] [,3] [1,] 3 9 15 [2,] 6 12 18 , , 2, 2 [,1] [,2] [,3] [1,] 4 12 20 [2,] 8 16 24
Outer() Function in R
A flexible tool for working with matrices and vectors in R is the outer() function. It enables you to create a new matrix or array by applying a function to every conceivable combination of the items from two input vectors. outer() function in R Programming Language is used to apply a function to two arrays.
Syntax: outer(X, Y, FUN = “*”)
Parameters:
- x, y: arrays
- FUN: function to use on the outer products, default value is multiply
A matrix or array with the same dimensions as the outer product of X and Y is what the outer() function in R produces. The function FUN is applied to the relevant pair of elements from X and Y to produce each element of the result.
Contact Us