Is there a more elegant way of converting a list of variables into a data.table object?
This does not give the desired result.
require(data.table)
set.seed(1)
Var.List <- list(a=sample(letters, 10, rep=T),b=rnorm(10), c=rnorm(10))
data.table(Var.List)
The following does give the desired result, but is slow with big lists/tables. Is there a better way? I run into this problem quite often when aggregating results from the foreach package.
data.table(as.data.frame(Var.List))
a b c
1: g -0.8204684 -0.04493361
2: j 0.4874291 -0.01619026
3: o 0.7383247 0.94383621
4: x 0.5757814 0.82122120
5: f -0.3053884 0.59390132
6: x 1.5117812 0.91897737
7: y 0.3898432 0.78213630
8: r -0.6212406 0.07456498
9: q -2.2146999 -1.98935170
10: b 1.1249309 0.61982575
Edit: The best solution (h.t. Arun) is to just do as.data.table(Var.List), invoking as.data.table()'s ready-made "list" method.
Just like data.frame(), data.table() will accept a data.frame, a matrix, or an arbitrary number of vectors as inputs, processing them via its ... argument.
Taking advantage of the latter option, you can use do.call() to construct a data.table from a list of such vectors:
do.call(data.table, Var.List)
a b c
1: g -0.8204684 -0.04493361
2: j 0.4874291 -0.01619026
3: o 0.7383247 0.94383621
4: x 0.5757814 0.82122120
5: f -0.3053884 0.59390132
6: x 1.5117812 0.91897737
7: y 0.3898432 0.78213630
8: r -0.6212406 0.07456498
9: q -2.2146999 -1.98935170
10: b 1.1249309 0.61982575
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With