Outer() Function in R

Outer() Function in detail

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 possible combination of the elements from two input vectors. The outer() function in R 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 multiplication (*)

The outer() function in R produces a matrix or array with dimensions corresponding to the outer product of X and Y. The function FUN is applied to the respective pair of elements from X and Y to generate each element of the result.

Examples

Example 1: Outer Product of Two Vectors

# Initializing two arrays of elements
x <- c(2, 4, 6, 8, 10)
y <- c(3, 6, 9)

# Multiplying elements of x with elements of y
outer(x, y)

Output:

[,1] [,2] [,3]
[1,]    6   12   18
[2,]   12   24   36
[3,]   18   36   54
[4,]   24   48   72
[5,]   30   60   90

Example 2: Outer Function for a Vector and a Single Value

# Initializing a vector and a single value
a <- 1:7
b <- 5

# Adding elements of a with b
outer(a, b, "+")

Output:

[,1]
[1,]    6
[2,]    7
[3,]    8
[4,]    9
[5,]   10
[6,]   11
[7,]   12
Types of outer() Functions

Since the outer() function is general, you can define custom functions and use them with outer(). Below are some commonly used types:

1. Arithmetic Functions

The most common use of outer() is for performing arithmetic operations such as addition, subtraction, multiplication, and division on two vectors. The operators +-*/%%, and %/% can be applied.

Example:

x <- 2:4
y <- 5:7
outer(x, y, FUN = "-")

Output:

[,1] [,2] [,3]
[1,]   -3   -4   -5
[2,]   -2   -3   -4
[3,]   -1   -2   -3

2. Statistical Functions

Statistical operations can also be applied using outer(). For example, suppose we want to find the product of two matrices.

Example:

# Creating two matrices
A <- matrix(2:7, nrow = 2, ncol = 3)
B <- matrix(1:4, nrow = 2, ncol = 2)

# Multiplying the two matrices using the outer function
outer(A, B, "*")

Output:

, , 1, 1

     [,1] [,2] [,3]
[1,]    2    4    6
[2,]    3    5    7

, , 2, 1

     [,1] [,2] [,3]
[1,]    4    8   12
[2,]    6   10   14

, , 1, 2

     [,1] [,2] [,3]
[1,]    6   12   18
[2,]    9   15   21

, , 2, 2

     [,1] [,2] [,3]
[1,]    8   16   24
[2,]   12   20   28

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *