s-news
[Top] [All Lists]

how to get rid of this double for loop?

To: <s-news@lists.biostat.wustl.edu>
Subject: how to get rid of this double for loop?
From: "Danni Wang" <wangdn@uclink4.berkeley.edu>
Date: Thu, 31 Oct 2002 17:02:55 -0800
Importance: Normal
In-reply-to: <53173E7EC9822349ACC7FBEC177BDDDA16585C@hqmail2.nrgenergy.com>
Reply-to: <wangdn@uclink4.berkeley.edu>
Happy Halloween, Group,

I used a double for loop to replace NAs in the matrix with a new value. My
matrix is 20000 by 30. It is very slow to run the loop. I don't know how to
use apply() and is.na() to make it faster. Could you give some suggestions?

My code:

for (i in 1:nrow(data)){
   for (j in 1:ncol(data){
        if (is.na(data[i,j])) { data[i,j] <- data[i-1,j] }
    }
}

Thanks very much,

Danni


<Prev in Thread] Current Thread [Next in Thread>