[英]Extracting specific elements from a character vector
我有一個角色矢量
a=c("Mom", "mother", "Alex", "Betty", "Prime Minister")
我只想提取以“ M”開頭的單詞(上下兩個都)
這個怎么做?
我試過使用grep()
, sub()
和此函數的其他變體,但我做對了。
我希望輸出是“媽媽”和“母親”的字符向量
a[startsWith(toupper(a), "M")]
普通grep
也可以
grep( "^m", a, ignore.case = TRUE, value = TRUE )
#[1] "Mom" "mother"
基准
湯姆的答案(startsWith)是贏家,但仍有一些改進的余地(請查看startsWith2
的代碼)
microbenchmark::microbenchmark(
substr = a[substr(a, 1, 1) %in% c("M", "m")],
grepl = a[grepl("^[Mm]", a)],
grep = grep( "^m", a, ignore.case = TRUE, value = TRUE ),
stringr = unlist(stringr::str_extract_all(a,regex("^M.*",ignore_case = T))),
startsWith1 = a[startsWith(toupper(a), "M")],
startsWith2= a[startsWith(a, c("M", "m"))]
)
# Unit: nanoseconds
# expr min lq mean median uq max neval
# substr 1808 2411.0 3323.19 3314 3917 8435 100
# grepl 3916 4218.0 5438.06 4820 6930 8436 100
# grep 3615 4368.5 5450.10 4820 6929 19582 100
# stringr 50913 53023.0 55764.10 54529 55132 174432 100
# startsWith1 1506 2109.0 2814.11 2711 3013 17474 100
# startsWith2 602 1205.0 1410.17 1206 1507 3013 100
使用grepl
,其模式為^[Mm]
:
a[grepl("^[Mm]", a)]
[1] "Mom" "mother"
這是模式^[Mm]
含義:
^ from the start of the string
[Mm] match either a lowercase or uppercase letter M
grepl
函數的工作原理是斷言輸入模式至少匹配一次,因此我們不必關心字符串的其余部分。
使用stringr
library(stringr)
unlist(str_extract_all(a,regex("^M.*",ignore_case = T)))
[1] "Mom" "mother"
substr
是一個非常易於處理的基本R函數:
a[substr(a, 1, 1) %in% c("M", "m")]
# [1] "Mom" "mother"
而且由於您提到了sub()
所以您可以這樣做(不過不一定建議這樣做):
a[sub("(.).*", "\\1", a) %in% c("M", "m")]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.