简体   繁体   English

在R中使用for循环的Replicate()

[英]Replicate() using for loop in R

I'd like to create a large number of samples in R and store them in a variable. 我想在R中创建大量样本并将其存储在变量中。 I did some research and probably the best way is to use replicate() 我做了一些研究,可能最好的方法是使用copy()

record <- replicate(5000, sample(c(0,1), size = 60, replace = T,prob=c(0.9,0.1)))

My question is how would I do it using for loop? 我的问题是我该如何使用for循环? I can create 5000 samples using for loop but how do I store them? 我可以使用for循环创建5000个样本,但是如何存储它们呢?

x <- 'something here' #I want to store them in x

for (i in 1:5000)
    {record <- sample(c(0,1), size = 60, replace = T,prob=c(0.9,0.1))
    'x += record'}

Edit: The line X+= record is confusing. 编辑:X + =行记录令人困惑。 Here is my best shot at explaining that, in python I'd create a list and inside that list there'd be 5000 other lists each containing a different sample 这是我最好的解释,这是在python中创建的一个列表,该列表中还有5000个其他列表,每个列表包含一个不同的示例

I see no point in using a for loop; 我看不到使用for循环的意义。 nor is there a need for replicate . 也不需要replicate

You can draw 5000 * 60 independent samples directly using 您可以直接使用绘制5000 * 60独立样本

smpl <- sample(c(0, 1), size = 60 * 5000, replace = TRUE, prob = c(0.9, 0.1))

If you want to store smpl in a matrix, you can recast the vector as a matrix , eg 如果要将smpl存储在矩阵中,则可以将向量重铸为matrix ,例如

mat <- matrix(smpl, ncol = 5000)

This will give you a 60 x 5000 matrix, where every column contains 5000 random samples drawn from a distribution with p(0) = 0.9 and p(1) = 0.1 . 这将为您提供60 x 5000矩阵,其中每列包含从p(0) = 0.9p(1) = 0.1的分布中抽取的5000随机样本。

This will be faster than using a for loop or replicate . 这将比使用for循环或replicate更快。

What about 关于什么

x <- list() # or x <- c() or x <- data.frame()

for (i in 1:5000){
    record <- sample(c(0,1), size = 60, replace = T,prob=c(0.9,0.1))
    x[[i]] <- record # or x <- c(x, record) or x <- rbind(x, record)
}

But yeah, not using a loop is probably better here, as indicated above. 但是,是的,如上所述,不使用循环可能会更好。

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

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