[R] Inverse function to 'which'?

Peter Holzer holzer at stat.math.ethz.ch
Mon Jul 9 10:12:21 CEST 2001


Henrik Bengtsson writes:
 > Is there an inverse function to 'which' available, which creates a logical
 > vector/matrix from indices? I wrote my own, but if there is a standard
 > function I would like to use that instead. Example:
 > 
 > x <- c(TRUE, TRUE, FALSE, TRUE, FALSE, FALSE)
 > unwhich(which(x))            # [1] TRUE TRUE FALSE TRUE
 > unwhich(which(x), length(x)) # [1] TRUE TRUE FALSE TRUE FALSE FALSE
 > 
 > y <- matrix(x, nrow=3, ncol=2)
 > unwhich(which(y, arr.ind=TRUE))          # "Minimum" size
 > unwhich(which(y, arr.ind=TRUE), dim(y))  # Same dimensions as y

The following function does what you want:

unwhich <- function (which, dim = max(which)) {
  y <- array(logical(length(which)), dim = dim)
  y[which] <- TRUE
  y
}

Cheers, Peter
 
 > Thanks
 > 
 > Henrik Bengtsson
 > h e n r i k b @ b r a j u . c o m
 > 
 > -.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
 > 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
 > _._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._
-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
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