简体   繁体   中英

How to repeat the For loop in r?

I am trying to create a for loop and, in each iteration, replace the values in aux_j.

In an example, my function ranging from 1 to box_size[1]*ninbox2[1] calculates the values in the vector aux_j[1] and (you can do it manually run the code below) passes to j=1+1 = 2 and, repeating the steps, calculates for aux_j[2].

It may seem strange but I need that to replace the values in each step. The last "aux_j" will contain only the values for iteration [22].

aux_j<-0
box_size<-c(4,5,6,7,8,9,10,11,12,14,16,18,20,22,24,27,30,33,36,40,44,48)
ninbox2 <-c(50,40,33,28,25,22,20,18,16,14,12,11,10,9,8,7,6,6,5,5,4,4)

j<-1 # up here only need run one time

for(i in 1:(box_size[j]*ninbox2[j])){ 


  if(i==1){

    aux_j[1]<- box_size[j] 

  }

  else if(i>=2){
    aux_j[i] <- aux_j[i-1]+ box_size[j]


  }

}

    j<-j+1




aux_j

Try the following.

The first way of computing aux_j is with a double for loop, but every time through the innermost loop, the values of aux_j will be rewritten. This is just your code simplified.

aux_j_size <- max(box_size*ninbox2)
aux_j <- numeric(aux_j_size)
for(j in seq_along(ninbox2)){
  for(i in 1:(box_size[j]*ninbox2[j])){ 
    aux_j[i] <- box_size[j] 
    if(i >= 2){
      aux_j[i] <- aux_j[i - 1] + aux_j[i]
    }
  }
}
aux_j

The second way also uses a double loop, an outer lapply loop and an inner for loop. The vectors aux_j are computed in the for loop and each of them is saved in the list aux_list . In the end, the list's members are assigned names aux_01 , aux_02 , etc.

aux_list <- lapply(seq_along(ninbox2), function(j){
  aux_j <- numeric(box_size[j]*ninbox2[j])
  for(i in seq_len(box_size[j]*ninbox2[j])){ 
    aux_j[i] <- box_size[j] 
    if(i >= 2){
      aux_j[i] <- aux_j[i - 1] + aux_j[i]
    }
  }
  aux_j
})

names(aux_list) <- sprintf("aux_%02d", seq_along(ninbox2))
aux_list

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM