Simple pattern matching and replacement with R

For pattern matching, grep and grepl are commonly used. The general syntax is grep(pattern, text):

grep("think",c("I think","therefore I am")) # Gives the index of the match 
grepl("think",c("I think","therefore I am")) # Gives a logical vector of the match 

It is possible to replace only characters that match using gsub, regexpr, and other pattern matching and replacement functions in R:

gsub("th","ab",c("I think","therefore I am")) # To replace all occurrences of "th" in the text 

For users who are familiar with regular expressions, R also supports regex patterns (for example, PCRE, and so on):

gsub("t.","ab",c("I think","therefore I am"), perl=T) # To replace all occurrences of "th" in the text 
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.189.186.109