Question

Say we have the following data table:

> DT1
  11 12 13 14
  15 16 17 18
  19 20 21 22
  23 24 25 26
  27 28 29 30
  31 32 33 34
  ...

And this the new output:

> DT2
  11 12 13 14 15 16 17 18 19 20 21 22
  23 24 25 26 27 28 29 30 31 32 33 34
  ...

I realized this with a data.frame and a for loop. How can I realise it with data.table? The dataset is much bigger and the for loop in the data.frame is a littlebit slow.

A little example of my loop:

for ...
  DT2[1,1:4]  <- DT1[1,]
  DT2[1,5:8]  <- DT1[2,]
  DT2[1,9:12] <- DT1[3,]
  DT2[2,1:4]  <- DT1[4,]
  ...
end for

Can I improve it with data.table's? How is the syntax for the loop?

Was it helpful?

Solution

If all entries in dt1 are of the same type (either numbers or strings or TRUE/FALSE), then this will be easier and faster to do with reindexing/reshaping matrices:

dt1 <- matrix(11:34, ncol=4, byrow=TRUE)
dt1
#     [,1] [,2] [,3] [,4]
#[1,]   11   12   13   14
#[2,]   15   16   17   18
#[3,]   19   20   21   22
#[4,]   23   24   25   26
#[5,]   27   28   29   30
#[6,]   31   32   33   34
dt2 <- matrix(as.vector(t(dt1)), ncol=12, byrow=TRUE)
dt2
#     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12]
#[1,]   11   12   13   14   15   16   17   18   19    20    21    22
#[2,]   23   24   25   26   27   28   29   30   31    32    33    34
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top