How to subset data with advance string matching

前端 未结 2 1558
误落风尘
误落风尘 2021-02-03 10:33

I have the following data frame from which I would like to extract rows based on matching strings.

> GEMA_EO5
gene_symbol  fold_EO  p_value                            


        
2条回答
  •  自闭症患者
    2021-02-03 11:25

    To do partial matching you'll need to use regular expressions (see ?grepl). Here's a solution to your particular problem:

    ##Notice that the first element appears in 
    ##a row containing commas
    l = c( "NM_013433", "NM_001386", "NM_020385")
    

    To test one sequence at a time, we just select a particular seq id:

    R> subset(GEMA_EO5, grepl(l[1], GEMA_EO5$RefSeq_ID))
      gene_symbol fold_EO p_value                           RefSeq_ID BH_p_value
    5       TNPO2   4.708 1.6e-23 NM_001136195,NM_001136196,NM_013433  1.538e-20
    

    To test for multiple genes, we use the | operator:

    R> paste(l, collapse="|")
    [1] "NM_013433|NM_001386|NM_020385"
    R> grepl(paste(l, collapse="|"),GEMA_EO5$RefSeq_ID)
    [1] FALSE  TRUE FALSE FALSE  TRUE FALSE  TRUE
    

    So

    subset(GEMA_EO5, grepl(paste(l, collapse="|"),GEMA_EO5$RefSeq_ID))
    

    should give you what you want.

提交回复
热议问题