简体   繁体   English

是否有一种方法可以重新生成数据 500 次?

[英]Is the a way to regenerate data for 500 times?

library(MASS)

# set seed and create data vectors
#set.seed(98989) <- for replicating results of betas in 1-2 1-3
sample_size <- 200                                       
sample_meanvector <- c(3, 4)                                   
sample_covariance_matrix <- matrix(c(2, 1, 1, 2),
                                   ncol = 2)

# create bivariate normal distribution
sample_distribution <- mvrnorm(n = sample_size,
                               mu = sample_meanvector, 
                               Sigma = sample_covariance_matrix)
#Convert the datatype
df_sample_distribution <- as.data.frame(sample_distribution)

Is there a way to put this entire chunk of code in a loop and regenerate it for 500 times?有没有办法将整个代码块放入循环中并重新生成 500 次? Would be even better if i can store them somewhere.如果我能把它们存放在某个地方就更好了。

You might use replicate()你可以使用replicate()

library(MASS)
out <- replicate(3, simplify = FALSE, {sample_size <- 200                                       
          sample_meanvector <- c(3, 4)                                   
          sample_covariance_matrix <- matrix(c(2, 1, 1, 2),
                                             ncol = 2)
          
          # create bivariate normal distribution
          sample_distribution <- mvrnorm(n = sample_size,
                                         mu = sample_meanvector, 
                                         Sigma = sample_covariance_matrix)
          #Convert the datatype
          df_sample_distribution <- as.data.frame(sample_distribution)

          head(df_sample_distribution) # for shorter output
          })

out
#> [[1]]
#>         V1       V2
#> 1 3.195478 4.393699
#> 2 2.553590 5.065685
#> 3 2.822811 2.389559
#> 4 2.267116 4.076016
#> 5 1.659459 3.830608
#> 6 1.377554 4.009023
#> 
#> [[2]]
#>           V1       V2
#> 1  2.8850139 3.107203
#> 2  3.0313680 5.163229
#> 3  3.8649482 4.594017
#> 4  3.2747060 4.085805
#> 5 -0.1640264 3.628542
#> 6  3.6504855 4.747372
#> 
#> [[3]]
#>          V1       V2
#> 1 1.3230817 4.075396
#> 2 3.6049470 6.293968
#> 3 6.1211276 7.673592
#> 4 5.2955379 6.736665
#> 5 0.9032304 2.606501
#> 6 3.6034566 3.880563

Created on 2022-12-04 with reprex v2.0.2创建于 2022-12-04,使用reprex v2.0.2

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

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