Return a Vector of Positions

classic Classic list List threaded Threaded
2 messages Options
Reply | Threaded
Open this post in threaded view
|

Return a Vector of Positions

allan miller-2
Hello,

I wrote a version of which.na (similar to S's) in R that returns a
vector of positions at which NA appears in the target vector v:

which.na<-function(v) {
  retv <- c()
  for (i in 1:length(v)) {
     if (is.na(v[i])) {
       retv<-append(i, retv, after = length(retv))
     }
     
  }
  return(retv)
}

nv <- c(2,4,NA,NA)
nas<-which.r(nv)
print(nas)

[run]


 > source("which.r")
[1] 4 3
 >

Two questions about this:

(1) It seems that append actually "prepends"

(2) Is there a more simpler way to build the vector of positions (versus
using append in a loop, as above), using functions such as match() and
apply()?

Thank You.

______________________________________________
[hidden email] mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html
Reply | Threaded
Open this post in threaded view
|

Re: Return a Vector of Positions

hadley wickham
> (2) Is there a more simpler way to build the vector of positions (versus
> using append in a loop, as above), using functions such as match() and
> apply()?

How about
which.na <- function(x) which(is.na(x))
?

Hadley

______________________________________________
[hidden email] mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html