Replace rbind in for-loop with lapply? (2nd circle of hell)

前端 未结 2 1673
盖世英雄少女心
盖世英雄少女心 2020-12-10 08:30

I am having trouble optimising a piece of R code. The following example code should illustrate my optimisation problem:

Some initialisations and a function definitio

相关标签:
2条回答
  • 2020-12-10 09:05

    A bit to long for comment, so I put it here: If columns is known in advance:

        myfunction <- function(frame){
        athing = 0
           if(columns == 5){
           athing = 100
           }
           else{
           athing = 1000
           }
        value[colums+1] = athing
        return(value)}
    
        apply(myframe, 2, myfunction)
    

    If columns is not given via environment, you can use:

    apply(myframe, 2, myfunction, columns) with your original myfunction definition.

    0 讨论(0)
  • 2020-12-10 09:12

    The reason that using rbind in a loop like this is bad practice, is that in each iteration you enlarge your solution data frame and then copy it to a new object, which is a very slow process and can also lead to memory problems. One way around this is to create a list, whose ith component will store the output of the ith loop iteration. The final step is to call rbind on that list (just once at the end). This will look something like

    my.list <- vector("list", nrow(myframe))
    for(i in 1:nrow(myframe)){
        # Call all necessary commands to create values
        my.list[[i]] <- values
    }
    solution <- rbind(solution, do.call(rbind, my.list))
    
    0 讨论(0)
提交回复
热议问题