confused doughnut
confused doughnut

Reputation: 47

How to repeat a for loop in R for n times?

I am trying to repeat a for loop in R for a fixed number of times. Here is a sample of the code I want to repeat

for (i in 1:nrow(data)) {
  if (i>130){
    data$deltas[i]=-((-data$p[i]))*data$alphas[i]
  }
  else  {
    data$deltas[i]=
      ((-(((data$p[i+1])-(data$p[i])))*data$alphas[i]) + data$deltas[i+1])
  }
}

I do not have any conditions that need to be met, just need to run the same code over the same dataset n times.

Upvotes: 1

Views: 3394

Answers (1)

akrun
akrun

Reputation: 887058

If we want to repeat the for loop 'n' times, create a function with the for loop

f1 <- function(data, ival) {  
       
      for(i in head(seq_len(nrow(data)), -1)) {
        if(i > ival) {
         data$deltas[i] <- -((-data$p[i])) * data$alphas[i]
        
        } else  {
         data$deltas[i] <- ((-(((data$p[i+1]) - (data$p[i]))) * 
                            data$alphas[i]) + data$deltas[i+1])
        }
      
      }
    return(data)

  }

and assign the data on each iteration

n <- 10
for(i in seq_len(n)) data <- f1(data, ival = 130)

Using a small reproducible example

set.seed(24)
df1 <- data.frame(deltas = rnorm(10), p = runif(10), alphas = rnorm(10))

-input

df1
#         deltas          p      alphas
#1  -0.545880758 0.09393471 -0.46906069
#2   0.536585304 0.55225375 -0.33498679
#3   0.419623149 0.72516981  1.53625216
#4  -0.583627199 0.13792462  0.60999453
#5   0.847460017 0.22296603  0.51633570
#6   0.266021979 0.68767062 -0.07430856
#7   0.444585270 0.07648914 -0.60515695
#8  -0.466495124 0.59973018 -1.70964518
#9  -0.848370044 0.63014766 -0.26869311
#10  0.002311942 0.04663503 -0.64859151



n <- 10
for(i in seq_len(n)) df1 <- f1(df1, ival = 5)

-output

df1
#         deltas          p      alphas
#1   0.832142549 0.09393471 -0.46906069
#2   0.617163102 0.55225375 -0.33498679
#3   0.559238507 0.72516981  1.53625216
#4  -0.342918176 0.13792462  0.60999453
#5  -0.291043381 0.22296603  0.51633570
#6  -0.051099814 0.68767062 -0.07430856
#7  -0.046287932 0.07648914 -0.60515695
#8  -1.025325821 0.59973018 -1.70964518
#9  -0.169316331 0.63014766 -0.26869311
#10  0.002311942 0.04663503 -0.64859151

Upvotes: 2

Related Questions