Monday, 27 July 2015

R: grep : Search for a string in a character vector

“grep” function is used to search for a string in character vector.

Usage
grep(pattern, x, ignore.case = FALSE, perl = FALSE, value = FALSE, fixed = FALSE, useBytes = FALSE, invert = FALSE)

pattern : Pattern represents a regular expression, to be matched in character vector.

x: Represents a character vector

ignore.case : If it is true, then pattern matching ignore case, else not.

perl : If it is true, then perl compatible regular expressions are used, else not.

value : if FALSE, a vector containing the (integer) indices of the matches determined by grep is returned, and if TRUE, a vector containing the matching elements themselves is returned.

fixed: If TRUE, pattern is a string to be matched as is.

useBytes : If TRUE the matching is done byte-by-byte rather than character-by-character.

invert : If TRUE return indices or values for elements that do not match.

> x <- c("Hello", "Hari", "How", "Are", "you", "He", "Hat")
> grep("you", x)
[1] 5
> 
> grep("ha", x)
integer(0)
> 
> grep("Ha", x)
[1] 2 7
> 
> grep("Ha", x, invert=TRUE)
[1] 1 3 4 5 6
> 
> grep("Ha", x, invert=TRUE, value=TRUE)
[1] "Hello" "How"   "Are"   "you"   "He"   
> 
> grep("Ha", x, value=TRUE)
[1] "Hari" "Hat" 
> 
> grep("ha", x, invert=TRUE, value=TRUE, ignore.case=TRUE)
[1] "Hello" "How"   "Are"   "you"   "He"   
> 
> grep("ha", x, invert=TRUE, value=TRUE, ignore.case=FALSE)
[1] "Hello" "Hari"  "How"   "Are"   "you"   "He"    "Hat"  
>



Prevoius                                                 Next                                                 Home

No comments:

Post a Comment