Home > front end >  how to do for-loop in R
how to do for-loop in R

Time:06-21

aa <-order(maxstaCode$ gateInComingCnt,decreasing=TRUE)[1:10]
aa
 [1]  11 121  19  79  13  21  43  10  15 138
for(i in aa){
maxinnum<-c(maxstaCode$gateInComingCnt[i])
}
maxinum

I wanted to use the loop to bring the numbers of aa into the index value in the chart in sequence, and runs out of the value corresponding to the index value the result below

[1] 6235770 2805043 2772432 2592227 2461369 2428441 1990890 1821025 1595055
[10] 1491299

but it turned out:

[1] 1491299

CodePudding user response:

In the for loop, the issue was that maxinum is updated on each iteration, resulting in returning the last value. Instead we need to use c(maxinum, ...)

maxinum <- c()
for(i in aa){
   maxinum <- c(maxinum, maxstaCode$gateInComingCnt[i])
}
maxinum
  • Related