将变量列表转换为data.table对象(Converting a List of Variables into a data.table object)

编程入门 行业动态 更新时间:2024-10-25 19:21:18
将变量列表转换为data.table对象(Converting a List of Variables into a data.table object)

是否有更优雅的方法将变量列表转换为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.61982575

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

最满意答案

编辑:最好的解决方案(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.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

更多推荐

本文发布于:2023-08-05 14:27:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1434064.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:转换为   变量   对象   列表   data

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!