如何使用for循环进行多次采样?

How to use for loops to take multiple samples?

设置是:“假设你有 10,000 人,其中 6,000 人是民主党人。我们从这个假设的人口中模拟调查抽样。首先,在 R 中生成人口向量。然后,创建 500 个大小为 n = 1,000 的随机样本。"

到目前为止我的代码是:

pop<-c(rep("Democrat", 6000), rep("Republican", 4000))


nTrials <- 500
n <- 1000
results <- rep(NA, nTrials)

for(i in 1:nTrials)
{
  sampled <- sample(x=pop, size=n, replace=FALSE)
  results[i]<- sampledpop<-c(rep(1, 6000), rep(0, 4000))


nTrials <- 500
n <- 1000
results <- matrix(data=NA, ncol = nTrials, nrow = n)
Y<-matrix(data=NA, ncol=nTrials, nrow=1)

for(i in 1:nTrials)
{
  sampled <- sample(x=pop, size=n, replace=TRUE)
  results[,i]<- sampled
  Y[,i]<- sum(results[,i])
}

我认为这段代码有效,但我担心如何判断矩阵是否正确填充。

试试这个

replicate(500L, sample(c("Democrat", "Republican"), 1000L, replace = TRUE, prob = c(0.6, 0.4)), simplify = FALSE)

或者这个

pop <- c(rep("Democrat", 6000L), rep("Republican", 4000L))
replicate(500L, sample(pop, 1000L), simplify = FALSE)

您可以使用查看功能轻松查看已保存的对象。 Link to View Function in R.

我们还可以在我们的 R 代码中加入一行,在击键之后停止执行。 Stack exchange thread covering this

将两者放在一起,我们就可以将两行代码放入一个循环中,其中一行向我们显示最终输出的当前版本,另一行暂停循环直到我们继续。这将使我们逐步探索循环的行为。以您的循环之一为例:

for(i in 1:nTrials)
{
  sampled <- sample(x=pop, size=n, replace=TRUE)
  results[,i]<- sampled
  Y[,i]<- sum(results[,i])
  View(Y)
  readline(prompt="Press [enter] to continue")
}

请记住,这将持续进行指定的试验次数。

您可以限制试验次数,但您无法确保获得相同的结果,因此我们可以对代码进行中断。 link to info about the break statement. This lets us interrupt a for loop early, assuming we are happy with how things are building up. To make the break really shine, lets pair it with some user input, you can choose if you'd like to continue or not. link for collecting user input in r

所以然后结合所有这些我们得到类似的东西:

for(i in 1:nTrials)
{
  sampled <- sample(x=pop, size=n, replace=TRUE)
  results[,i]<- sampled
  Y[,i]<- sum(results[,i])
  View(Y,)
  interrupt = readline(prompt="Enter 1 for next loop, 0 to exit: ")
  if (interrupt == 0) {break}
}

就其价值而言,到目前为止,您的代码在我看来非常完美。