1

I have a character string that looks like below and I want to delete lines that doesn't have any value after '_'. How do I do that in R?

 [985] "Pclo_"                "P2yr13_ S329"         "Basp1_ S131"         
 [988] "Stk39_ S405"          "Srrm2_ S351"          "Grin2b_ S930"        
 [991] "Matr3_ S604"          "Map1b_ S1781"         "Crmp1_"              
 [994] "Elmo1_"               "Pcdhgc5_"             "Sp4_"                
 [997] "Pbrm1_"               "Pphln1_"              "Gnl1_ S33"           
[1000] "Kiaa1456_"
  • 2
    Does this answer your question? [How to determine if a string "ends with" another string in R?](https://stackoverflow.com/questions/26188663/how-to-determine-if-a-string-ends-with-another-string-in-r) – slava-kohut Jul 09 '20 at 23:13

2 Answers2

1

We can use grep

grep("_$", v1, invert = TRUE, value = TRUE)

Or endsWith

v1[!endsWith(v1, "_")]
akrun
  • 874,273
  • 37
  • 540
  • 662
0

We can use substring to get the last character in the vector and select if it is not "_".

x <- c("Pclo_","P2yr13_ S329","Basp1_ S131")
x[substring(x, nchar(x)) != '_']
#[1] "P2yr13_ S329" "Basp1_ S131" 

Last character can be extracted using regex as well with sub :

x[sub('.*(.)$', '\\1', x) != '_']
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213