[R] vector of NA indices

Martin Maechler maechler at stat.math.ethz.ch
Thu Jul 15 08:51:21 CEST 1999


>>>>> "BDR" == Prof Brian D Ripley <ripley at stats.ox.ac.uk> writes:

    BDR> On Wed, 14 Jul 1999, Friedrich Leisch wrote:
    >> >>>>> On Wed, 14 Jul 1999 04:09:21, >>>>> Peter B Mandeville (PBM)
    >> wrote:
    >> 
    PBM> I have a vector Pes with 600 elements some of which are NA's. How
    PBM> can I form a vector of the indices of the NA's.
    >>
    PBM> for(i in 1:600) if(is.na(Pes[i])) print(i)
    >>
    PBM> prints the indices of the NA's but I can't figure out how to put
    PBM> the results in a vector.
    >>  try this:
    >> 
    >> x <- (1:length(Pes))[is.na(Pes)]

    BDR> Tip: that sort of thing often fails for a length 0 vector. The
    BDR> `approved' spell is

    BDR> seq(along=Pes)[is.na(Pes)]

    BDR> In this case it does not matter as the subscript is of length 0,
    BDR> but it has floored enough library/package writers to be worth
    BDR> thinking about.

Good teaching about seq() vs.  1:n 

However, the solution I gave 

     which(is.na(Pes))

is the one I stilly really recommend; 
it does deal with 0-length objects, and it keeps names when there are some,
and it has an `arr.ind = FALSE' argument to return array indices instead of
vector indices when so desired.


Martin Maechler <maechler at stat.math.ethz.ch>	http://stat.ethz.ch/~maechler/
Seminar fuer Statistik, ETH-Zentrum SOL G1	Sonneggstr.33
ETH (Federal Inst. Technology)	8092 Zurich	SWITZERLAND
phone: x-41-1-632-3408		fax: ...-1086			<><
-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._



More information about the R-help mailing list