Subsetting a string based on pre- and suffix

柔情痞子 提交于 2019-12-24 04:19:10

问题


I have a column with these type of names:

sp_O00168_PLM_HUMAM   
sp_Q8N1D5_CA158_HUMAN  
sp_Q15818_NPTX1_HUMAN  
tr_Q6FGH5_Q6FGH5_HUMAN  
sp_Q9UJ99_CAD22_HUMAN  

I want to remove everything before, and including, the second _ and everything after, and including, the third _.

I do not which to remove based on number of characters, since this is not a fixed number.

The output should be:

PLM  
CA158    
NPTX1  
Q6FGH5  
CAD22

I have played around with these, but don't quite get it right..
library(stringer)
str_sub(x,-6,-1)


回答1:


> gsub(".*_.*_(.*)_.*", "\\1", "sp_O00168_PLM_HUMAM") 
[1] "PLM"



回答2:


That’s not really a subset in programming terminology1, it’s a substring. In order to extract partial strings, you’d usually use regular expressions (pretty much regardless of language); in R, this is accessible via sub and other related functions:

pattern = '^.*_.*_([^_]*)_.*$'
result = sub(pattern, '\\1', strings)

1 Aside: taking a subset is, as the name says, a set operation, and sets are defined by having no duplicate elements and there’s no particular order to the elements. A string by contrast is a sequence which is a very different concept.




回答3:


Another possible regular expression is this:

sub("^(?:.+_){2}(.+?)_.+", "\\1", vec)
# [1] "PLM"    "CA158"  "NPTX1"  "Q6FGH5" "CAD22" 

where vec is your vector of strings.

A visual explanation:



来源:https://stackoverflow.com/questions/21407361/subsetting-a-string-based-on-pre-and-suffix

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!