File: l_which.r

package info (click to toggle)
r-bioc-destiny 3.4.0-1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 11,800 kB
  • sloc: cpp: 174; javascript: 141; sh: 12; python: 6; makefile: 2
file content (33 lines) | stat: -rw-r--r-- 1,232 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#' Logical which
#' 
#' Inverse of \link[base]{which}. Converts an array of numeric or character indices to a logical index array.
#' This function is useful if you need to perform logical operation on an index array but are only given numeric indices.
#' 
#' Either \code{nms} or \code{len} has to be specified.
#' 
#' @param idx       Numeric or character indices.
#' @param nms       Array of names or a sequence. Required if \code{idx} is a character array
#' @param len       Length of output array. Alternative to \code{nms} if \code{idx} is numeric
#' @param useNames  Use the names of nms or idx
#' 
#' @return Logical vector of length \code{len} or the same length as \code{nms}
#' 
#' @examples
#' all(l_which(2, len = 3L) == c(FALSE, TRUE, FALSE))
#' all(l_which(c('a', 'c'), letters[1:3]) == c(TRUE, FALSE, TRUE))
#' 
#' @export
l_which <- function(idx, nms = seq_len(len), len = length(nms), useNames = TRUE) {
	rv <- logical(len)
	if (is.character(nms)) # we need names here so that rv[idx] works
		names(rv) <- nms
	
	if (useNames && !is.null(names(idx)))
		names(rv)[idx] <- names(idx)
	
	rv[idx] <- TRUE
	
	if (!useNames) # if we don't want names, we'll remove them if we added them before
		names(rv) <- NULL
	rv
}