To find all unique combinations of two vectors in R, you can use two different functions expand.grid() and crossing() function from tidyr package.

The following methods show how you can do it with syntax.

Method 1: Use expand.grid() Function

expand.grid(vector1, vector2)


Method 2: Use crossing() Function

library(tidyr)

crossing(Temperature, Humidity)


The following examples show how to find all unique combination of two vector using expand.grid() and crossing() function in R.

## Using expand.grid() Function

Let’s see how we can use expand.grid() function in R:

# Define vectors
Machine=c("A","B","C","D")
Humidity=c(5,7,1,2)

# Find all unique combinations of Temperature and Humidity
u <- expand.grid(Machine,Humidity)

# Show combinations
print(u)


Output:

   Var1 Var2
1     A    5
2     B    5
3     C    5
4     D    5
5     A    7
6     B    7
7     C    7
8     D    7
9     A    1
10    B    1
11    C    1
12    D    1
13    A    2
14    B    2
15    C    2
16    D    2


Here the output shows all unique combinations for Machine and Humidity vector.

## Using crossing() Function

Let’s see how we can use crossing() function from tidyr package in R:

# Import package
library(tidyr)

# Define vectors
Machine=c("A","B","C","D")
Humidity=c(5,7,1,2)

# Find all unique combinations of Temperature and Humidity
u <- crossing(Temperature, Humidity)

# Display all unique combinations of Temperature and Humidity
print(u)


Output:

    Machine Humidity
<chr>      <dbl>
1 A              1
2 A              2
3 A              5
4 A              7
5 B              1
6 B              2
7 B              5
8 B              7
9 C              1
10 C              2
11 C              5
12 C              7
13 D              1
14 D              2
15 D              5
16 D              7


Here the output shows all unique combinations of Machine and Humidity vector using crossing() function.