0

I have a column col1 from df1

col1
A
B
C
D
E

I have col2 from df2

col2
1
2
3

I want a new df df3 combining both col2 and col1

col2     col1
 1        A
 1        B
 1        C
 1        D
 1        E
 2        A
 2        B
 2        C
 2        D
 2        E
 3        A
 ...
 3        E

I used

n = 5; test = do.call("rbind", replicate(n, col2, simplify = FALSE))
n = 3; test = do.call("rbind", replicate(n, col1, simplify = FALSE))

And then merge data together. it's really not efficient with big data. what's the best way to solve this problem?

NightDog
  • 91
  • 7

1 Answers1

0

Use merge with a cross join, for a base R option:

df1 <- data.frame(col1=c("A", "B", "C", "D", "E"))
df2 <- data.frame(col2=c(1:3))

merge(df1, df2, by=NULL)

   col1 col2
1     A    1
2     B    1
3     C    1
4     D    1
5     E    1
6     A    2
7     B    2
...
15    E    3

Demo

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360