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 thatouter()will take.Y2: This represents the second vector or array thatouter()will take.Func: This is the operation we want to perform on the arrays or vectors. The default argument of theFuncparameter 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 vectorsmyarray1<- c(7, 2, 1, 5, 6)myarray2<- c(6, 3, 2)# invoking outer() functionouter(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 vectorsVect<- c(7, 2, 1, 5, 6)Vect1<- c(6, 3, 2)# calling outer() functionresult1<- outer(Vect, Vect1, function (Vect, Vect1) Vect+1+Vect1)# printing resultsprint(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
outerfunction call toresult1. This is used to easily read and understand the code. After that, theouterfunction 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 add1in the values of theVectand then perform addition on the newVectandVect1. -
Line 7: We display the final matrix.