0

I have:

dataDT <- data.table(A = 1:3, B = 1:3)
dataDT
   A B
1: 1 1
2: 2 2
3: 3 3

I want:

dataDT <- data.table(A = c(1:3, 1:3), B = c(1:3, 1:3))
dataDT

   A B
1: 1 1
2: 2 2
3: 3 3
4: 1 1
5: 2 2
6: 3 3

i.e. create x copies of duplicate and append after the bottom row.

I've tried (results aren't what I need):

dataDT1 <- splitstackshape::expandRows(dataset = dataDT, count = 2, count.is.col = FALSE)   # order not correct
dataDT1
   A B
1: 1 1
2: 1 1
3: 2 2
4: 2 2
5: 3 3
6: 3 3

Also (results aren't what I need):

dataDT2 <- rbindlist(list(rep(dataDT, 2)))   # it creates columns
dataDT2
   A B A B
1: 1 1 1 1
2: 2 2 2 2
3: 3 3 3 3

Can anyone recommend a correct and efficient way of doing it?

LeGeniusII
  • 900
  • 1
  • 10
  • 28
  • 1
    Easiest one: `dataDT[rep(dataDT[, .I], 2)]` ([see also here](https://stackoverflow.com/a/57919688/2204410)) – Jaap Sep 13 '19 at 08:12

1 Answers1

2

You can do it with rep:

> x = 2; dataDT[rep(seq_len(nrow(dataDT)), x), ]
   A B
1: 1 1
2: 2 2
3: 3 3
4: 1 1
5: 2 2
6: 3 3

or with rbindlist and replicate:

> x = 2; rbindlist(replicate(x, dataDT, simplify = F))
   A B
1: 1 1
2: 2 2
3: 3 3
4: 1 1
5: 2 2
6: 3 3
mt1022
  • 16,834
  • 5
  • 48
  • 71