从R中的字符串向量中提取单个单词

时间:2015-07-28 21:30:56

标签: r string stringr

假设我有一个像下面那样的字符串向量,我想创建一个包含TRUE的逻辑向量,如果字符串中出现“white”,“bull”或“tiger”(注意不是whitetip)如果不这样做,则为FALSE。我如何在R中这样做呢?我试图使用stringr的str_detect(),但结果给出了'whitetip'的TRUE(我不知道如何为每个类别使用str_detect()...即我必须创建多个逻辑向量-1对于我的3类白虎和公牛中的每一类)。任何帮助都会很棒,谢谢!

<ui-gmap-google-map center="map.center" zoom="map.zoom" id="map-canvas">
  <ui-gmap-marker coords="map.center" icon="map.icon" idKey="1">
  </ui-gmap-marker>
</ui-gmap-google-map>

2 个答案:

答案 0 :(得分:4)

这是一种可以匹配所有字符串的方法

sapply(c("white","bull","tiger"), function(x) {
    grepl(paste0("\\b",x,"\\b"), string)
})

这给出了

      white  bull tiger
 [1,] FALSE FALSE  TRUE  # tiger?
 [2,] FALSE  TRUE FALSE  # thought to involve a 2.7 m [9'], 400-kb bull
 [3,]  TRUE FALSE FALSE  # 4 m to 5 m [13' to 16.5'] white
 [4,] FALSE FALSE FALSE  # oceanic whitetip shark, 2.5 to 3m
 [5,]  TRUE FALSE FALSE  # white
 [6,]  TRUE FALSE FALSE  # white
 [7,] FALSE  TRUE FALSE  # bull
 [8,]  TRUE FALSE FALSE  # white
 [9,] FALSE FALSE FALSE  # oceanic whitetip shark, 2.5m
[10,] FALSE FALSE  TRUE  # tiger
[11,]  TRUE FALSE FALSE  # white, >6'
[12,] FALSE  TRUE FALSE  # bull, 6'

答案 1 :(得分:1)

If you need to extract the relevant word, you could use stringr::str_extract:

str_extract(string, "\\b(bull|tiger|white)\\b")

# [1] "tiger" "bull"  "white" NA      "white" "white" "bull"  "white" NA     
#[10] "tiger" "white" "bull"