# What is the outer function in R

An array is a collection of the same data type values stored at contiguous memory locations. The arrays in R Programming language support basic mathematical operations, e.g. addition, multiplication, etc.

## Outer function in R

The `outer()` function takes two arrays and a mathematical operation or a user-defined function as the parameters. If no operation or user-defined function is passed as an argument, it considers multiplication (*) to be the operation by default.

Moreover, `outer()` function in the R language helps to apply any `'other'` function on our arrays. The other function may be addition, multiplication, etc. The `outer()` function can also be used to apply a user-defined function on the arrays.

## Syntax

``outer(array1, array2,"Operation")``

## Parameters

Outer() in R takes the following argument values.

• `array1`: array1 is the first array passed to the function.
• `array2`: array2 is the second array passed to the function.
• `Operation`:Operation” is the function that the user wants to apply to the arrays. If no operation is passed, it will be considered multiplication (‘*’) by default.

## Return value

The outer function returns a 2d array having columns equal to the number of items in array1, and rows equal to the number of items in array2. The operation which we passed inside the function is applied at corresponding entries of each array.

## Explanation

Now, let’s implement outer function in R via coding examples under different use cases.

### Example#1

In this example, we are going to multiply each element of `array2` with every element of `array1`, and print the resulting matrix.

```array1 <- c(1, 1, 2, 2, 3, 3)
array2 <- c(1, 2, 3, 4)
print(outer(array1, array2))
```
• Line 1: Populate the first array with the given values.
• Line 2:  Populating the second array with the given values
• Line 3: Applying the `outer()` function on the arrays. Since no operation is given by the user, So, multiplication `(*)` shall be applied since it is the default operation.

## Output

### Example#2

In this example, we are going to subtract each element of `array2` from every element of `array1`, and print the resulting matrix.

```array1 <- c(5, 4, 3, 2, 1)
array2 <- c(1, 2, 3)
print(outer(array1, array2, "-"))
```
• Line 1: Populate the first array with the given values.
• Line 2:  Populating the second array with the given values
• Line 3: Applying the `outer()` function on the arrays. Since `'-'` has been passed as an argument along with the arrays. So, subtraction `'-'` shall be the operation this time, instead of the default operation.

You may like: