Pattern Searching in R

Pattern Searching in R, Selecting a subset of data based on character inputs that match more abstract patterns is frequently desirable.

Also, it can be quite helpful to have the ability to search and replace character strings within a character vector.

Data Science applications in Retail » finnstats

grep-pattern searching in R

The grep() function looks for matches to a pattern within a vector and returns the index of all corresponding elements.

Choose only ‘SITE’ values that have an A in them.

X<-c(15,24,7,14,12)
Y<-c(9,11,15,13,15)
TEMP<-c(33,32,42,22,36)
SITE<-c("A1","A2","A3","A4","A5")
exp<-c(list(SITE=SITE, COORDINATES=paste(X,Y,sep=","),TEMP=TEMP))
exp
$SITE
[1] "A1" "A2" "A3" "A4" "A5"
$COORDINATES
[1] "15,9" "24,11" "7,15" "14,13" "12,15"
$TEMP
[1] 33 32 42 22 36
grep("A",exp$SITE)
[1] 1 2 3 4 5
exp$SITE[grep("A",exp$SITE)]
[1] "A1" "A2" "A3" "A4" "A5"

Any valid regular expression is included by default in the pattern, giving you a lot of flexibility when searching for patterns.

How to Draw Plots with Textures and Patterns in R » finnstats

A data frame from the exp list

EXP<-as.data.frame(exp)

Just the rows with the “SITE” value of either an A, B, or C followed by 1 should be chosen.

EXP[grep("[A-C]1",EXP$SITE),]
SITE COORDINATES TEMP
1   A1        15,9   33

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *

2 × 3 =