Create a combination of data frame and vector

I know that expand.grid is to create all combinations of given vectors. But is there a way to generate all combinations of a data frame and a vector, taking each row in the data frame as unique. For instance,

 df <- data.frame(a = 1:3, b = 5:7) c <- 9:10 

how to create a new data frame that is a combination of df and c without df extension:

 df.c: abc 1 5 9 2 6 9 3 7 9 1 5 10 2 6 10 3 7 10 

Thanks!

+4
source share
3 answers

It may not scale when your framework has more than two columns per row, but you can just use expand.grid in the first column and then merge second column.

 df <- data.frame(a = 1:3, b = 5:7) c <- 9:10 combined <- expand.grid(a=df$a, c=c) combined <- merge(combined, df) > combined[order(combined$c), ] acb 1 1 9 5 3 2 9 6 5 3 9 7 2 1 10 5 4 2 10 6 6 3 10 7 
+6
source

You can also do something like this

 do.call(rbind,lapply(9:10, function(x,d) data.frame(d, c=x), d=df))) # or using rbindlist as a fast alternative to do.call(rbind,list) library(data.table) rbindlist(lapply(9:10, function(x,d) data.frame(d, c=x), d=df))) 

or

 rbindlist(Map(data.frame, c = 9:10, MoreArgs = list(a= 1:3,b=5:7))) 
+3
source

The easiest way for me is: merge(df, as.data.frame(c))

  abc 1 1 5 9 2 2 6 9 3 3 7 9 4 1 5 10 5 2 6 10 6 3 7 10 
+3
source

All Articles