复制矩阵以形成列表

时间:2016-04-06 19:55:07

标签: r matrix

a是一个矩阵。

a<-matrix(c(2,2,1,1,1,2,1,2,1,1,2,1,1,1,1,1,1,2,2,2,1,2,1,1),6)

我想复制矩阵“a”3次以形成列表。

我试过了:

as.list(rep(a,3))

但它不起作用。 我的预期结果如下:

[[1]]
     [,1] [,2] [,3] [,4]
[1,]    2    1    1    2
[2,]    2    2    1    2
[3,]    1    1    1    1
[4,]    1    1    1    2
[5,]    1    2    1    1
[6,]    2    1    2    1

[[2]]
     [,1] [,2] [,3] [,4]
[1,]    2    1    1    2
[2,]    2    2    1    2
[3,]    1    1    1    1
[4,]    1    1    1    2
[5,]    1    2    1    1
[6,]    2    1    2    1

[[3]]
     [,1] [,2] [,3] [,4]
[1,]    2    1    1    2
[2,]    2    2    1    2
[3,]    1    1    1    1
[4,]    1    1    1    2
[5,]    1    2    1    1
[6,]    2    1    2    1

2 个答案:

答案 0 :(得分:4)

rep返回它收到的相同类型,因此如果你传递一个数字矩阵,它将尝试返回某种数字向量 - 而不是列表。但是,解决方案很简单:如果您需要列表,请将其传递给列表:

rep(list(a), 3)
# [[1]]
#      [,1] [,2] [,3] [,4]
# [1,]    2    1    1    2
# [2,]    2    2    1    2
# [3,]    1    1    1    1
# [4,]    1    1    1    2
# [5,]    1    2    1    1
# [6,]    2    1    2    1
# 
# [[2]]
#      [,1] [,2] [,3] [,4]
# [1,]    2    1    1    2
# [2,]    2    2    1    2
# [3,]    1    1    1    1
# [4,]    1    1    1    2
# [5,]    1    2    1    1
# [6,]    2    1    2    1
# 
# [[3]]
#      [,1] [,2] [,3] [,4]
# [1,]    2    1    1    2
# [2,]    2    2    1    2
# [3,]    1    1    1    1
# [4,]    1    1    1    2
# [5,]    1    2    1    1
# [6,]    2    1    2    1

答案 1 :(得分:2)

也许使用lapply:

lapply(1:3, function(i) a)

基准:

library(microbenchmark)

a <- matrix(c(2,2,1,1,1,2,1,2,1,1,2,1,1,1,1,1,1,2,2,2,1,2,1,1),6)

microbenchmark(
  replicate(3, a, simplify = FALSE),
  rep(list(a), 3),
  lapply(1:3, function(i) a),
  times = 10000)


# Unit: nanoseconds
#                               expr  min   lq      mean median   uq     max neval cld
#  replicate(3, a, simplify = FALSE) 5987 7127 8044.9371   7413 7983 1150921 10000   c
#                    rep(list(a), 3)    0  285  396.2066    285  570   15395 10000 a  
#         lapply(1:3, function(i) a) 1995 2566 3013.6994   2851 3136 1290902 10000  b