Combine each element with any other element of the object (cross-product)

I have two integer vectors, for example v1=c(1,2) and v2=c(3,4) , I want to combine and get this as a result (like data.frame or matrix):

 > combine(v1,v2) <--- doesn't exist 1 3 1 4 2 3 2 4 

This is the main case. Which is relatively slightly more complicated - to combine each row with each other row? For instance. Suppose we have two data.frames or matrices d1 and d2, and we want to combine them to get the following result:

 d1 1 13 2 11 d2 3 12 4 10 > combine(d1,d2) <--- doesn't exist 1 13 3 12 1 13 4 10 2 11 3 12 2 11 4 10 

How could I achieve this?

+4
source share
1 answer

For the simple case of vectors, expand.grid exists

 v1 <- 1:2 v2 <- 3:4 expand.grid(v1, v2) # Var1 Var2 #1 1 3 #2 2 3 #3 1 4 #4 2 4 

I do not know about a function that will automatically do what you want to do for dataframes (see edit)

We could do this relatively easily using expand.grid and cbind.

 df1 <- data.frame(a = 1:2, b=3:4) df2 <- data.frame(cat = 5:6, dog = c("a","b")) expand.grid(df1, df2) # doesn't work so let try something else id <- expand.grid(seq(nrow(df1)), seq(nrow(df2))) out <-cbind(df1[id[,1],], df2[id[,2],]) out # ab cat dog #1 1 3 5 a #2 2 4 5 a #1.1 1 3 6 b #2.1 2 4 6 b 

Edit: As Joran notes in the comments, merge does this for us for data frames.

 df1 <- data.frame(a = 1:2, b=3:4) df2 <- data.frame(cat = 5:6, dog = c("a","b")) merge(df1, df2) # ab cat dog #1 1 3 5 a #2 2 4 5 a #3 1 3 6 b #4 2 4 6 b 
+6
source

Source: https://habr.com/ru/post/1415741/


All Articles