Search code examples
rfor-loopexecute

R Code Taking Too Long To Run


I have the following code running and it's taking me a long time to run. How do I know if it's still doing its job or it got stuck somewhere.

noise4<-NULL;
for(i in 1:length(noise3))
{
    if(is.na(noise3[i])==TRUE)
    {
    next;
    }
    else
    {
    noise4<-c(noise4,noise3[i]);
    }
}

noise3 is a vector with 2418233 data points.


Solution

  • You just want to remove the NA values. Do it like this:

    noise4 <- noise3[!is.na(noise3)]
    

    This will be pretty much instant.

    Or as Joshua suggests, a more readable alternative:

    noise4 <- na.omit(noise3)
    

    Your code was slow because:

    1. It uses explicit loops which tend to be slow under the R interpreter.
    2. You reallocate memory every iteration.

    The memory reallocation is probably the biggest handicap to your code.