Search code examples
rfor-looppanel

R - How to speed up panel data construction process using for-loop


I am planning to construct a panel dataset and, as a first step, I am trying to create a vector that has 25 repetitive ids (same 25 ids to assign to each year later) for each 99537 unique observation. What I have so far is:

unique_id=c(1:99573) 
panel=c()

for(i in 1:99573){
x=rep(unique_id[i],25)
panel=append(panel,x)
}

The problem I have is the codes above are taking too much time. RStudio keeps processing and does not give me any output. Could there be any other ways to speed up the process? Please share any ideas with me.


Solution

  • We don't need a loop here

    panel <- rep(unique_id, each = 25)
    

    Benchmarks

    system.time(panel <- rep(unique_id, each = 25))
    #   user  system elapsed 
    #  0.046   0.002   0.047 
    
    length(panel)
    #[1] 2489325