从字符串中提取单词

时间:2018-12-19 10:12:24

标签: r string

我只想提取对象Scaffold和每个字符串的scaffold数量(例如Scaffold 6)。有任何想法吗?

 [2] "KQ415657.1 isolate UCB-ISO-001 unplaced genomic scaffold Scaffold5, whole genome shotgun sequence"   
   [3] "ABCD0100000.1  isolate UCB-ISO-001 Scaffold6_contig_1, whole genome shotgun sequence"                
   [4] "ABCDD0100001.1  isolate UCB-ISO-001 Scaffold8_contig_1, whole genome shotgun sequence"                
   [5] "ABCD0100002.1  isolate UCB-ISO-001 Scaffold2_contig_1, whole genome shotgun sequence"               
   [6] "ABCD0100003.1  isolate UCB-ISO-001 Scaffold6_contig_1, whole genome shotgun sequence"               
   [7] "ABCD0100004.1  isolate UCB-ISO-001 Scaffold2_contig_1, whole genome shotgun sequence"               
   [8] "ABCD0100005.1  isolate UCB-ISO-001 Scaffold7_contig_1, whole genome shotgun sequence"               
   [9] "ABCD0100006.1  isolate UCB-ISO-001 Scaffold8_contig_1, whole genome shotgun sequence"               

2 个答案:

答案 0 :(得分:1)

这是作为字符串向量存储还是在data.frame中存储?每行是否总是包含一个Scaffold字符串?

如果只是矢量:

STRING = c("This is some vector Scaffold1", "some Scaffold20 string with stuff")

stringr::str_split(string = STRING, pattern = " ") %>% 
    lapply(function(x) x[grepl("Scaffold", x)]) %>% 
    unlist()
[1] "Scaffold1"  "Scaffold20"

如果可以将其放在data.frame中,则可能会更整洁:

library(tidyverse)
data.frame(String = STRING, stringsAsFactors = F) %>% 
    separate(String, paste0("V", 1:8), remove = F) %>% 
    gather(key,val, starts_with("V")) %>% 
    filter(grepl("Scaffold", val)) %>% 
    select(-key)
                             String        val
1 some Scaffold20 string with stuff Scaffold20
2     This is some vector Scaffold1  Scaffold1

答案 1 :(得分:0)

听取Athanasia Mowinckel的回答。这是一个sapply选项。

STRING = c("This is some vector Scaffold1", "some Scaffold20 string with stuff")
sapply(str_extract_all(STRING,"Sca.*[0-9]"),"[")