简体   繁体   English

将向量从循环保存到列表或数据中

[英]Save vectors from loop into a list or data.frame R

I have to generate several iterations of some mathematical operations, which result in a vector of length 100 each time. 我必须生成一些数学运算的多次迭代,每次导致一个长度为100的向量。

I want to store each vector of n iterations into a list or data.frame, after running a for loop. 在运行for循环后,我想将n次迭代的每个向量存储到列表或data.frame中。

Basically, save my results (vector of length 100) into a list to be converted into a matrix or directly into a matrix. 基本上,将我的结果(长度为100的向量)保存到列表中,以转换为矩阵或直接转换为矩阵。

For instance: 例如:

for (i in 1:10){
     r <- rnorm(100,0,1)
     }

In each of the 10 iterations, r generates a vector of length 100. The final desired output is a data.frame with 100 rows and 10 columns, each column representing each of the generated iterations. 在10个迭代的每一个中,r生成长度为100的向量。最终的期望输出是具有100行和10列的data.frame,每列代表每个生成的迭代。

How to build such matrix or data.frame? 如何建立这样的矩阵或data.frame?

Many thanks 非常感谢

We can use replicate 我们可以使用replicate

replicate(10, rnorm(100))

If needed we can convert it into a dataframe (showing a smaller example for n = 5 ) 如果需要,我们可以将其转换为数据帧(显示n = 5一个较小示例)

set.seed(1234)
as.data.frame(replicate(10, rnorm(5)))

#       V1      V2       V3      V4      V5       V6      V7      V8      V9     V10
#1 -1.2071  0.5061 -0.47719 -0.1103  0.1341 -1.44820  1.1023 -1.1676  1.4495 -0.9685
#2  0.2774 -0.5747 -0.99839 -0.5110 -0.4907  0.57476 -0.4756 -2.1800 -1.0686 -1.1073
#3  1.0844 -0.5466 -0.77625 -0.9112 -0.4405 -1.02366 -0.7094 -1.3410 -0.8554 -1.2520
#4 -2.3457 -0.5645  0.06446 -0.8372  0.4596 -0.01514 -0.5013 -0.2943 -0.2806 -0.5238
#5  0.4291 -0.8900  0.95949  2.4158 -0.6937 -0.93595 -1.6291 -0.4659 -0.9943 -0.4968

Using a for loop you can do 使用for循环,您可以执行

# choose number of columns you need
ncolumns <- 10
# generate an "empty" matrix
m <- matrix(NA, 100, ncolumns)
# run for loop
for (i in 1:ncolumns){
  m[ , i] <- rnorm(100,0,1)
}

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

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