-2

Using these dataset:

[A]
100
200
300

[B]
A
B
C

I would like to make this column:

[A]   [B]
100    A
100    B
100    C
200    A
200    B
200    C
300    A
300    B
300    C

I would like to use rep function in R, but it does not work. How do I create this column?

jhyeon
  • 456
  • 4
  • 14

2 Answers2

2

With rep() as follows

data.frame(A=rep(c(100,200,300), c(3,3,3)),
               B=rep(c("A", "B", "C"), 3))
Patrik_P
  • 3,066
  • 3
  • 22
  • 39
  • 1
    Usually, it's a good idea to generalize the answer beyond the exact example. In this instance, the use of 3. Here, you could do `rep(A, each=length(B))` and `rep(B, length(A))`. – lmo Aug 27 '17 at 14:58
  • Thnx for tip, will do – Patrik_P Aug 27 '17 at 15:00
1

We can use expand.grid

d1 <- expand.grid(A = df1$A, B = df1$B)

Or with CJ

library(data.table)
CJ(A= df1$A, B= df1$B)

data

df1 <- data.frame(A = c(100, 200, 300), B = LETTERS[1:3], stringsAsFactors = FALSE)
akrun
  • 874,273
  • 37
  • 540
  • 662