johnny
johnny

Reputation: 631

Fastest way to convert a matrix to a data.table

What is the fastest way to convert a matrix like the following to a data.table?

mat <- matrix(1:9, nrow = 3)

1 2 3
4 5 6
7 8 9

I can convert this to a data.table with the code below

setDT(data.frame(mat))[]

But is this the fastest way? Can we do this without first converting it to a data.frame?

Upvotes: 3

Views: 944

Answers (2)

ThomasIsCoding
ThomasIsCoding

Reputation: 102900

Here are some examples to discuss about the speed of forming data.table, i.e., as.data.table, setDT(as.data.frame(mat)) and setDT(data.frame(mat)).

  • when rows are less than columns:
mat <- matrix(1:5e3, nrow = 5)
microbenchmark(unit = "relative",
               as.data.table(mat),
               setDT(as.data.frame(mat))[],
               setDT(data.frame(mat))[])

Unit: relative
                        expr      min       lq     mean   median       uq      max neval
          as.data.table(mat) 1.433084 1.417747 1.340552 1.413278 1.414386 1.070289   100
 setDT(as.data.frame(mat))[] 1.000000 1.000000 1.000000 1.000000 1.000000 1.000000   100
    setDT(data.frame(mat))[] 1.287526 1.281964 1.237544 1.284735 1.258662 1.186977   100
  • when rows are more than columns:
mat <- matrix(1:5e3, nrow = 5e2)
microbenchmark(unit = "relative",
               as.data.table(mat),
               setDT(as.data.frame(mat))[],
               setDT(data.frame(mat))[])

Unit: relative
                        expr      min       lq     mean   median       uq      max neval
          as.data.table(mat) 1.114003 1.041410 1.083238 1.070029 1.049262 1.254732   100
 setDT(as.data.frame(mat))[] 1.000000 1.000000 1.000000 1.000000 1.000000 1.000000   100
    setDT(data.frame(mat))[] 1.680208 1.467538 1.482018 1.511009 1.479438 1.440440   100

Remark: setDT(as.data.frame(mat))[] is the winner of speed

Upvotes: 4

Matt
Matt

Reputation: 7423

You could use a magrittr pipe:

mat <- matrix(1:9, nrow = 3) %>% data.table()

Without magrittr:

mat <- data.table(matrix(1:9, nrow = 3)) 

Upvotes: 1

Related Questions