user2300940
user2300940

Reputation: 2385

grep only exact matches from pattern

I would like to grep the rownames that match exacly to my pattern toMatch.

toMatch <- c("I-A", "I-AA", "I-AAA")
dat[grep(toMatch, rownames(dat)), ]

dat

hsa-miR-10b-5p_TACCCTGTAGAACCGAATTTGTAA_0;I-AA;0;g           3.939829e-01
hsa-miR-122-5p_TGGAGTGTGACAATGGTGTTTGATA_0;I-ATA;0;0         3.942306e-01
hsa-miR-122-5p_TGGAGTGTGGCAATGGTGTTTGAAA_10GA;I-AAA;0;0      3.948047e-01

out

 hsa-miR-10b-5p_TACCCTGTAGAACCGAATTTGTAA_0;I-AA;0;g           3.939829e-01
 hsa-miR-122-5p_TGGAGTGTGGCAATGGTGTTTGAAA_10GA;I-AAA;0;0      3.948047e-01

Upvotes: 1

Views: 144

Answers (2)

Sotos
Sotos

Reputation: 51582

Library stringr is good for manipulating strings,

dat <- dat[str_detect(dat$V1, toMatch),]
dat
#                                                       V1        V2
#1      hsa-miR-10b-5p_TACCCTGTAGAACCGAATTTGTAA_0;I-AA;0;g 0.3939829
#3 hsa-miR-122-5p_TGGAGTGTGGCAATGGTGTTTGAAA_10GA;I-AAA;0;0 0.3948047

Upvotes: 2

JeremyS
JeremyS

Reputation: 3525

You want grepl as it returns a string of T/F. grep/grepl only takes single string as input, it can't take a vector, you can add | (meaning or) between different things to grep.

dat[grepl("I-A|I-AA|I-AAA", rownames(dat)), ]

Upvotes: 5

Related Questions