简体   繁体   English

初始化R中的矩阵列表

[英]Initialize a list of matrices in R

I was wondering if there's a quick way to initialize a list of matrices in R. For example I'm looking for a (one-liner) to reproduce the same results as the following: 我想知道是否有一种快速的方法可以初始化R中的矩阵列表。例如,我正在寻找一种(单线)以再现与以下相同的结果:

output_array = list()
for(i in 1:10){
output_array[i] = diag(2)
}

Thanks! 谢谢!

还可以尝试以下* apply包装器:

replicate(10, diag(2), simplify=F)

This one liner should work 这一支班轮应该工作

rep(list(diag(2)), 10)

If you want the contents of the matrices to vary, then something like 如果您想改变矩阵的内容,那么类似

lapply(1:10, function(x) matrix(1:x^2, x, x)

will be more appropriate. 会更合适。 The contents of the anonymous function will obviously be something a bit more useful than my example, but the principle is the same 匿名函数的内容显然比我的示例有用,但是原理是相同的

Both replicate and rep have been recommended. 建议同时使用rep和rep。 FYI: The difference is the evaluation of the expression being passed. 仅供参考:区别在于对传递的表达式的求值。 'rep' evaluates it's arguments as input, whereas 'replicate' evaluates them inside the 'loop'. “ rep”将其参数作为输入进行评估,而“ replicate”在“循环”内部对其进行评估。

You can see this with random numbers. 您可以看到随机数字。 With replicate the numbers are different because the expression 'diag(rnorm(2))' is evaluated multiple times, whereas with rep, it's only evaluated once and the value is repeated. 使用重复时,数字是不同的,因为表达式'diag(rnorm(2))'会被多次评估,而使用rep时,它只会被评估一次,并且值会重复。

rep(list(diag(rnorm(2))),2) rep(列表(diag(rnorm(2))),2)

[[1]] [[1]

  [,1] [,2] 

[1,] 1.0844 0.0000 [1,] 1.0844 0.0000

[2,] 0.0000 -2.3457 [2,] 0.0000 -2.3457

[[2]] [[2]

  [,1] [,2] 

[1,] 1.0844 0.0000 [1,] 1.0844 0.0000

[2,] 0.0000 -2.3457 [2,] 0.0000 -2.3457

replicate(2,diag(rnorm(2))) 复制(2,diag(rnorm(2)))

, , 1 ,,1

  [,1] [,2] 

[1,] 0.42912 0.00000 [1,] 0.42912 0.00000

[2,] 0.00000 0.50606 [2,] 0.00000 0.50606

, , 2 ,,2

  [,1] [,2] 

[1,] -0.57474 0.00000 [1,] -0.57474 0.00000

[2,] 0.00000 -0.54663 [2,] 0.00000 -0.54663

This may or may not matter for you, but there are performance implications. 这可能对您无关紧要,但是会影响性能。

system.time(replicate(1000, diag(100),simplify=F)) system.time(replicate(1000,diag(100),simplify = F))

user system elapsed 用户系统已使用

0.640 0.032 0.674 0.640 0.032 0.674

system.time(rep(list(diag(100)),1000)) system.time(rep(list(diag(100)),1000))

user system elapsed 用户系统已使用

0.072 0.036 0.111 0.072 0.036 0.111

Try 尝试

lapply(1:10, diag, 2)

In your for loop you had to write [[ in output_array[[i]] = diag(2) 在for循环中,您必须编写[[output_array[[i]] = diag(2)

You can use an array : 您可以使用数组:

 h <- array(1:2, c(2,2,10))

h[,,2]        ####
     [,1] [,2]
[1,]    1    1
[2,]    2    2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM