Open In App

Outer() Function in R

Last Updated : 18 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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.

Example 1: Outer Product of Two Vector

R
# Initializing two arrays of elements
x <- c(1, 2, 3, 4, 5)
y<- c(2, 4, 6)

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

Explanation: Multiplying array x elements with array y elements, Here multiply (*) parameter is not used still this function take it as default

Example 2: outer Function for Vector and Single Value

R
x <- 1:8
y<- 4

outer(x, y, "+")

Output: 

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

Explanation: Multiplying array x elements with array y elements, Here multiply (*) parameter is not used still this function take it as default

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

Arithmetic operations such as addition, subtraction, multiplication, division, and modular operations are common use cases of the outer() function.

Example: Adding Elements from Two Vectors

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

The outer() function can also be used with statistical functions to perform operations like calculating the correlation between two vectors or applying other statistical measures.

Example: Matrix Multiplication Using outer()

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


Next Article

Similar Reads