gpt4 book ai didi

r - 将相同顺序的矩阵列表转换为数组

转载 作者:行者123 更新时间:2023-12-02 06:33:01 26 4
gpt4 key购买 nike

我有一个列表(由100个成员组成),每个成员的成员都是4 * 2矩阵。如何在不使用R中循环的情况下将此列表转换为尺寸为400 * 2的数组?

例如

A<-list()


A[[1]]
x y
85.56384 27.97745
85.58448 28.02133
85.60252 27.96366
85.62318 28.00753

等等,最后
A[[100]]
x y
85.58448 28.02133
85.60500 28.06502
85.62317 28.00754
85.64372 28.05122

我希望有
A <-

      x         y
85.56384 27.97745
85.58448 28.02133
85.60252 27.96366
85.62318 28.00753
: :
85.58448 28.02133
85.60500 28.06502
85.62317 28.00754
85.64372 28.05122


感谢您的帮助。

最佳答案

这是对建议的不同策略的基准测试。如果您有新的想法/策略,请随时进行更新。

# packages
require(data.table)
require(tidyr)
require(microbenchmark)
# data
lst <- replicate(100, matrix(rnorm(16), ncol=4), simplify=FALSE)
# benchmark test
microbenchmark(
do.call(rbind, lst)
,
Reduce(rbind, lst)
,
apply(simplify2array(lst), 2, rbind)
,
rbindlist(lapply(lst, data.frame))
,
unnest(lapply(lst, data.frame))
)

结果:
Unit: microseconds
expr min lq mean median uq max neval
do.call(rbind, lst) 43.290 47.9760 55.63858 52.8845 62.703 101.307 100
Reduce(rbind, lst) 542.236 570.7985 620.99652 585.3020 610.518 1871.272 100
apply(simplify2array(lst), 2, rbind) 311.061 345.2010 382.22978 368.6315 388.268 1563.782 100
rbindlist(lapply(lst, data.frame)) 11827.884 12472.3190 13092.57937 12823.0995 13595.841 15833.736 100
unnest(lapply(lst, data.frame)) 12371.905 12927.9765 13514.24261 13236.1360 14008.655 16121.143 100

出于好奇,我也对 data.frame输入执行了这些基准测试,结果大相径庭:
# packages
require(data.table)
require(tidyr)
require(microbenchmark)
# data
lst <- replicate(100, as.data.frame(matrix(rnorm(16), ncol=4)), simplify=FALSE)
# benchmark test
microbenchmark(
do.call(rbind, lst)
,
Reduce(rbind, lst)
,
apply(simplify2array(lapply(lst, as.matrix)), 2, rbind)
,
rbindlist(lst)
,
unnest(lst)
)

结果
Unit: microseconds
expr min lq mean median uq max neval
do.call(rbind, lst) 12406.716 12944.2660 13746.8552 13571.966 14564.056 16333.128 100
Reduce(rbind, lst) 36316.866 38450.7765 39894.9806 39299.610 40325.395 100949.158 100
apply(simplify2array(lapply(lst, as.matrix)), 2, rbind) 9577.717 9940.9930 10273.8674 10065.059 10291.996 12114.846 100
rbindlist(lst) 324.896 369.0770 397.7828 402.995 426.202 500.732 100
unnest(lst) 926.487 974.9095 1011.7322 1010.834 1033.596 1171.051 100

关于r - 将相同顺序的矩阵列表转换为数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28339514/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com