s-news
[Top] [All Lists]

Re: how to get rid of this double for loop?

To: wangdn@uclink4.berkeley.edu, s-news@lists.biostat.wustl.edu
Subject: Re: how to get rid of this double for loop?
From: Bill.Venables@CMIS.CSIRO.AU
Date: Fri, 1 Nov 2002 14:10:37 +1000
Danni Wang asks:

>  -----Original Message-----
> From:         Danni Wang [mailto:wangdn@uclink4.berkeley.edu] 
> Sent: Friday, November 01, 2002 11:03 AM
> To:   s-news@lists.biostat.wustl.edu
> Subject:      [S] how to get rid of this double for loop?
> 
> 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] }
>     }
> }
> 
        [WNV]  I presume you are assuming that the very first element of
every column is not missing and that you never get two consecutive missing
values in any column.  

        You did say this is a matrix and not a data frame.  If this is the
case and you are willing to make the above brave assumption there is a very
simple way to do it:

        k <- which(is.na(data))
        data[k] <- data[k-1]

        If it is a data frame the simple (if rather inelegant) way to do it
is to convert to a matrix first, do the trick and then convert back.  This,
of course, comes with its own set of brave assumptions, too.

        Bill Venables.

> Thanks very much,
> 
> Danni
> 
> --------------------------------------------------------------------
> This message was distributed by s-news@lists.biostat.wustl.edu.  To
> unsubscribe send e-mail to s-news-request@lists.biostat.wustl.edu with
> the BODY of the message:  unsubscribe s-news

<Prev in Thread] Current Thread [Next in Thread>
  • Re: how to get rid of this double for loop?, Bill . Venables <=