Home > Software design >  How to do a for loop in R?
How to do a for loop in R?

Time:10-26

hello i need to find the mean of a sample of random numbers in an interval between -1 and 1 with a confidence interval of 95 % and then repeat the process 50 times i am using a for cycle that calculates the means for the 50 repetitions but when i apply it to the confidence interval it doesn't calculate the standard deviation i have this code

for (i in 1:50) {
  n<-100
  z[i] <-runif(min=-1,max=1,n)
  m[i] <-mean(z[i])
  s[i] <-sd(z[i])
  sigma[i] <-1.96*(s[i] /sqrt(n)) 
  ls[i] <-m[i]  sigma[i]
  li[i] <-m[i] -sigma[i]
}

CodePudding user response:

You don't need a for loop, all functions you need to apply are vectorized, so you can do:

simulation <- function(n){
  z <-runif(min=-1,max=1,n)
  m <-mean(z)
  s <-sd(z)
  sigma <-1.96*(s /sqrt(n)) 
  ls <-m  sigma
  li <-m -sigma
  
  return(list(m=m, s=s, sigma=sigma, ls=ls, li=li))
}

Example

> set.seed(1)
> simulation(n=50)
$m
[1] 0.06518574

$s
[1] 0.544478

$sigma
[1] 0.1509216

$ls
[1] 0.2161073

$li
[1] -0.08573586

If you want to replicate the simulation function n times, then replicate can be helpful for you, see example:

> set.seed(1)
> replicate(5, simulation(n=50))
      [,1]        [,2]       [,3]          [,4]       [,5]       
m     0.06518574  0.00620252 -4.981729e-05 0.06993695 -0.04302099
s     0.544478    0.5295532  0.5554962     0.5348175  0.541016   
sigma 0.1509216   0.1467847  0.1539757     0.1482439  0.149962   
ls    0.2161073   0.1529872  0.1539259     0.2181808  0.106941   
li    -0.08573586 -0.1405821 -0.1540255    -0.0783069 -0.192983  

I ran 5 times simulation with size 50 and get a matrix with results.

CodePudding user response:

m <- c()
s <- c()
ls <- c()
li <- c()
n <- 100

for (i in 1:50) {
  z <-runif(min=-1,max=1,n)
  m[i] <-mean(z)
  s[i] <-sd(z)
  sigma <- 1.96*(s[i] /sqrt(n)) 
  ls[i] <- m[i]  sigma
  li[i] <- m[i] -sigma
}
  • Related