File: Grep.R

package info (click to toggle)
r-cran-lava 1.8.1%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,816 kB
  • sloc: sh: 13; makefile: 2
file content (35 lines) | stat: -rw-r--r-- 1,270 bytes parent folder | download | duplicates (4)
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
34
35
##' Finds elements in vector or column-names in data.frame/matrix
##' 
##' Pattern matching in a vector or column names of a data.frame or matrix.
##' @param x vector, matrix or data.frame.
##' @param pattern regular expression to search for
##' @param subset If TRUE returns subset of data.frame/matrix otherwise just the matching column names
##' @param ignore.case Default ignore case
##' @param ... Additional arguments to 'grep'
##' @return A data.frame with 2 columns with the indices in the first and the
##' matching names in the second.
##' @author Klaus K. Holst
##' @seealso \code{\link{grep}}, and \code{\link{agrep}} for approximate string
##' matching,
##' @keywords misc utilities
##' @examples
##' data(iris)
##' head(Grep(iris,"(len)|(sp)"))
##' @export
`Grep` <-
    function(x, pattern, subset=TRUE, ignore.case = TRUE,...) {
        if (is.data.frame(x))
            nn <- names(x)
        else if (is.matrix(x))
            nn <- colnames(nn)
        else nn <-  x
        ii <- grep(pattern,nn,ignore.case=ignore.case,...)
        if (subset) {
            if (is.matrix(x) || is.data.frame(x))
                return(x[,ii,drop=FALSE])
            else return(x[ii])
        }  
        res <- data.frame(index=ii,name=nn[ii]);
        res
    }