# How to pairs the elements of two vectors in R

###### Posted By: Anonymous

I would like to pair elements of two vectors in R. The order is important.

```
For example,
X= c(1:3)
Y= c(1:3)
I expect to have:
1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3
```

I would like to use ‘lapply’. My data is more complicated but the idea is the same. I just need to pair each element of the first vector with all element of the second vector.

## Solution

If *"order is important"* means that the "monotonic increase" is important, then simply

```
expand.grid(X, Y)
# Var1 Var2
# 1 1 1
# 2 2 1
# 3 3 1
# 4 1 2
# 5 2 2
# 6 3 2
# 7 1 3
# 8 2 3
# 9 3 3
```

However, if column-order (second column increments before first), then just reverse the order of arguments (inferring that the real problem has differing numbers) and reorder them post-function:

```
expand.grid(Y, X)[2:1]
# Var2 Var1
# 1 1 1
# 2 1 2
# 3 1 3
# 4 2 1
# 5 2 2
# 6 2 3
# 7 3 1
# 8 3 2
# 9 3 3
```

The column names are inferred from the arguments, so `expand.grid(X=X, Y=Y)`

will name them `X`

and `Y`

instead of `Var#`

.

###### Answered By: Anonymous

Disclaimer: This content is shared under creative common license cc-by-sa 3.0. It is generated from StackExchange Website Network.