Repeat loop does not leave first position

Asked

Viewed 35 times

-2

The exercise is:

Using the function repeat, gere 1000 samples of normal distribution, each of equal sample size n and mean and standard deviation parameters equal to µ and σ, respectively. Choose the values for n, µ and σ.

For each generated database, calculate Z = (¯x − µ)/(σ/p(n)) in which is the sample average.

Calculate the proportion of samples that lead to values for Z smaller than -1,96 or greater than 1,96.

I was trying to calculate first ¯x, but I couldn’t even do that.

Follows the code:

f10 <- function(n, mean, sigma) {

  lista <- numeric(1000)

  i <- 1

  repeat{

    output <- rnorm(n, mean = mean, sd = sigma)

    lista[i] <- mean(output)

    if(i>1000) break()
  }

  i <- i+1

  return(lista)
}

1 answer

1


The counter needs to be inside the repeat, before checking the condition:

f10 <- function(n, mean,sigma) {
  lista <- numeric(1000)
  i <- 1
  repeat {
    output <- rnorm(n, mean = mean, sd = sigma)
    lista[i] <- mean(output)
    i <- i + 1
    if (i > 1000) break()
  }
  return(lista)
}

As it was, the value of i was always 1 when checking the condition for the break.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.