What is the outer() function in R?

Overview

The R programming language allows us to perform basic mathematical functions between two arrays with the help of a function called outer(). Listed below are some of its applications:

  • It can be used with a vector and single value or with two vectors.
  • It can also implement user-defined functions on vectors.
  • It can be used to create tables, power sets, and so on.

Syntax


outer(X1, Y2, Func = “…”)

Parameters

It takes the following argument values:

  • X1: This represents the first vector or array that outer() will take.
  • Y2: This represents the second vector or array that outer() will take.
  • Func: This is the operation we want to perform on the arrays or vectors. The default argument of the Func parameter is to perform multiplication between the given arrays or vectors.

Note: We can also use the operator symbols(+ or *) instead of the function.

Example 1

# creating two vectors
myarray1<- c(7, 2, 1, 5, 6)
myarray2<- c(6, 3, 2)
# invoking outer() function
outer(myarray1, myarray2,"+")

Explanation

  • Line 2: We assign values to myarray1. These values are also used as the number of rows a resultant matrix would contain.
  • Line 3: We assign values to myarray2. These values are also used as the number of columns a resultant matrix would contain.
  • Line 5: We use the outer() function to add two arrays.

Example 2

# creating 2 vectors
Vect<- c(7, 2, 1, 5, 6)
Vect1<- c(6, 3, 2)
# calling outer() function
result1<- outer(Vect, Vect1, function (Vect, Vect1) Vect+1+Vect1)
# printing results
print(result1)

Explanation

  • Line 2: We assign values to Vect. These values are also used as the number of rows a resultant matrix would contain.

  • Line 3: We assign values to Vect1. These values are also used as the number of columns a resultant matrix would contain.

  • Line 5: We assign the result of the outer function call to result1. This is used to easily read and understand the code. After that, the outer function is applied with the first two input arguments (Vect, Vect1). This will give values to the array. Then the function is used again with two variables (Vect, Vect1). We tell the compiler to first add 1 in the values of the Vect and then perform addition on the new Vect and Vect1.

  • Line 7: We display the final matrix.

Free Resources