[R] Making routine faster by using apply instead of for-loop

Etienne Stockhausen einohr2002 at web.de
Tue Jan 12 19:58:38 CET 2010


Hey everybody,

I have a small problem with a routine, which prepares some data for
plotting.
I've made a small example:

    c=10
    mat=data.frame(matrix(1:(c*c),c,c))
    row.names(mat)=seq(c,1,length=c)
    names(mat)=c(seq(2,c,length=c/2),seq(c,2,length=c/2))
    v=as.numeric(row.names(mat))
    w=as.numeric(names(mat))
    for(i in 1:c)
    { for(j in 1:c)
    {
    if(v[j]+w[i]<=c)(mat[i,j]=NA)
    }}

This produces exactly the data I need to go on, but if I increase the
constant c ,to for instance 500 , it takes a very long time to set the NA's.
I've heard there is a much faster way to set the NA's using the command
apply( ), but I don't know how.
I'm looking forward for any ideas or hints, that might help me.

Best regards

Etienne



More information about the R-help mailing list