Generate combination of data frame and vector

r

Solution

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

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), ]
  a  c b
1 1  9 5
3 2  9 6
5 3  9 7
2 1 10 5
4 2 10 6
6 3 10 7

Problem

I know `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 by 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 the combination of `df` and `c` without expanding `df`: ``` df.c: a b c 1 5 9 2 6 9 3 7 9 1 5 10 2 6 10 3 7 10 ``` Thanks!

Original source