1

I would like to extract specific strings with the pattern gene=something from one column in R.

An example of input:

df <- 'V1 
       ID=gene92;DbX;gene=BH1;genePro
       ID=gene91;DbY;gene=BH2;genePro;inf2
       ID=gene90;DbY;gene=BH3;genePro;inf2'
df <- read.table(text=df, header=T)

The example of the expected output:

dfout <- 'V1 
         gene=BH1
         gene=BH2
         gene=BH3'
    dfout <- read.table(text=dfout, header=T)

Some idea to accomplish that?

2 Answers 2

4
library(stringr)
str_extract(df$V1, 'gene=BH[0-9]+')
#[1] "gene=BH1" "gene=BH2" "gene=BH3"
Sign up to request clarification or add additional context in comments.

2 Comments

Assuming gene names could be variable and not always be BH and number, you could try str_extract(df$v1, 'gene=(.*?);') and gsub out that semicolon?
I just went with the example. It can of course be more generalized via sub
1

You may also use

gsub(".*(gene=.*?)(;|$).*", "\\1", df$V1)
# [1] "gene=BH1" "gene=BH2" "gene=BH3"

so that we match only the part gene=... that follows anything, .*, and is followed by ; or the end of the string, ;|$.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.