Amanda
Amanda

Reputation: 63

Simulation in R, for loop

I am trying to simulate the data for 10 times in R but I did not figure out how to achieve that. The code is shown below, you could run it in R straightway! When I run it, it will give me 5 numbers of "w" as output, I think this is only one simulation, but actually what I want is 10 different simulations of that 5 numbers.

I know I will need to write a for loop for it but I did not get that, could anyone help please?

# simulate 10 times

# try N = 10, for loop?
# initial values w0 and E

w0=1000
E= 1000
data = c(-0.02343731, 0.045509474 ,0.076144158,0.09234636,0.0398257)
constant = exp(cumsum(data))
exp.cum = cumsum(1/constant)
w=constant*(W0 - exp.cum)- E
w

Upvotes: 2

Views: 6038

Answers (1)

BarkleyBG
BarkleyBG

Reputation: 664

You'll want to generate new values of data in each simulation. Do this within the curly brackets that follow the for loop. Then, before closing the curly brackets, be sure to save your statistical output in the appropriate position in a object, like a vector. For a simple example,

W0=1000
E= 1000
n_per_sim <- 5
num_sims <- 10

set.seed(12345) #seed is necessay for reproducibility
sim_output_1 <- rep(NA, times = num_sims) #This creates a vector of 10 NA values

for (sim_number in 1:num_sims){ #this starts your for loop
data <- rnorm(n=n_per_sim, mean=10, sd=2) #generate your data
average <- mean(data)
sim_output_1[sim_number] <- average #this is where you store your output for each simulation
}
sim_output_1 #Now you can see the average from each simulation

Note that if you want to save five values from each simulation, you can make use a matrix object instead of a vector object, as shown here

matrix_output <- matrix(NA, ncol=n_per_sim, nrow=num_sims) #This creates a 10x5 matrix

for (sim_number in 1:num_sims){ #this starts your for loop
  data <- rnorm(n=n_per_sim, mean=10, sd=2) #generate your data

  constant = exp(cumsum(data))
  exp.cum = cumsum(1/constant)
  w=constant*(W0 - exp.cum)- E
  matrix_output[sim_number, ] <- w #this is where you store your output for each simulation
}
matrix_output #Now you can see the average from each simulation

Upvotes: 2

Related Questions