简体   繁体   中英

combine each item from one list with each item of another in r

I am trying to combine two vectors of sequential numbers in order to produce a matrix from which i can plot a grid. specifically my vectors contain longitude and latitude data respectively, but for simplicity sake, lets say i have:
matrix(seq(1, 3, 1)) [,1] [1,] 1 [2,] 2 [3,] 3
and
matrix(seq(1, 3, 1)) [,1] [1,] 1 [2,] 2 [3,] 3


and all i want is:
[,1] [,2] [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 above is fake and not actually from R) I've tried using a nested for loop to no avail. This seems way too simple to be giving me such trouble.

You seem to be looking for expand.grid()

a <- 1:3
b <- 1:3

expand.grid(a=a,b=b)
#   a b
# 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

## Or perhaps, if order matters to you
rev(expand.grid(b=b,a=a))
#   a b
# 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

You can do that with merge :

m1 <- 1:3
m2 <- 1:3
merge(m1, m2, by=NULL)
  x y
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

The advantage of using merge is that if you have a data.frame instead of vectors, it can easily deal with it:

m1<- data.frame(x=1:3, a=rnorm(3))
m2 <- data.frame(y=1:3, b=rnorm(3))
merge(m1, m2, by=NULL)
  x          a y          b
1 1 -0.6827197 1 -0.2046336
2 2 -1.5920405 1 -0.2046336
3 3  1.7696125 1 -0.2046336
4 1 -0.6827197 2  0.1738251
5 2 -1.5920405 2  0.1738251
6 3  1.7696125 2  0.1738251
7 1 -0.6827197 3  0.5166421
8 2 -1.5920405 3  0.5166421
9 3  1.7696125 3  0.5166421

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM