Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make grepl function specific?

Tags:

r

extract

My data frame is shown as below. I need extract the data of a specific row according to the name of "geneID" column one by one. I use grepl function.

#Data frame:geneDf  
geneID=c("EGFR","Her2","PTENPP","PTEN")
patient1=c(12,23,56,23)
patient2=c(23,34,11,6)
patient3=c(56,44,32,45)
patient4=c(23,64,45,23)
geneDf=data.frame(patient1,patient2,patient3,patient4,geneID)

geneDf
  patient1 patient2 patient3 patient4 geneID
1       12       23       56       23   EGFR
2       23       34       44       64   Her2
3       56       11       32       45 PTENPP
4       23        6       45       23   PTEN

The first three rows work well.

targetGene<-subset(geneDf,grepl(geneDf$geneID[1],geneDf$geneID))
targetGene
  patient1 patient2 patient3 patient4 geneID
1       12       23       56       23   EGFR

When I extract the data of the 4th row, I get this:

targetGene<-subset(geneDf,grepl(geneDf$geneID[4],geneDf$geneID))
targetGene
  patient1 patient2 patient3 patient4 geneID
3       56       11       32       45 PTENPP
4       23        6       45       23   PTEN

It seems other data,in this case, the 3rd row of "geneID" column, which includes the content of the 4th row is picked up too. What's wrong with my command? How to make it only pick up the data of a certain row each time?

like image 319
Lei Avatar asked Sep 26 '26 20:09

Lei


2 Answers

You may need word boundary i.e. \\b or use

subset(geneDf, grepl(paste0('^', geneID[4], '$'), geneID))
#  patient1 patient2 patient3 patient4 geneID
#4       23        6       45       23   PTEN

Or

subset(geneDf, grepl(paste0('\\b', geneID[4], '\\b'), geneID))
#   patient1 patient2 patient3 patient4 geneID
#4       23        6       45       23   PTEN
like image 130
akrun Avatar answered Sep 28 '26 09:09

akrun


@akrun has answered your specific question, but if you are looking to create subsets of your data according to another variable, you may also be interested in the split function:

split(geneDf, geneDf$geneID)
## $EGFR
##   patient1 patient2 patient3 patient4 geneID
## 1       12       23       56       23   EGFR
## 
## $Her2
##   patient1 patient2 patient3 patient4 geneID
## 2       23       34       44       64   Her2
## 
## $PTEN
##   patient1 patient2 patient3 patient4 geneID
## 4       23        6       45       23   PTEN
## 
## $PTENPP
##   patient1 patient2 patient3 patient4 geneID
## 3       56       11       32       45 PTENPP
## 
like image 30
A5C1D2H2I1M1N2O1R2T1 Avatar answered Sep 28 '26 11:09

A5C1D2H2I1M1N2O1R2T1



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!