是否有更优雅的方法将变量列表转换为data.table对象?
这不会产生预期的结果。
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)以下确实给出了期望的结果,但是对于大列表/表格来说速度很慢。 有没有更好的办法? 在汇总来自foreach包的结果时,我经常遇到这个问题。
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.61982575Is 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最满意答案
编辑:最好的解决方案(ht Arun)就是执行as.data.table(Var.List) ,调用as.data.table()现成的"list"方法。
就像data.frame() , data.table()将接受data.frame,矩阵或任意数量的向量作为输入,通过其...参数处理它们。
利用后一个选项,您可以使用do.call()从这些向量列表中构造data.table :
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.61982575Edit: 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更多推荐
发布评论