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?
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
@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
##
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With