我正在寻找一种grep方法来获取第一个空格之前的字符串中的字符.
我已经破解了以下功能,因为我无法弄清楚如何使用grep类型命令来执行此操作R.
有人可以帮助grep解决方案 - 如果有的话......
beforeSpace <- function(inWords) {
vapply(inWords, function(L) strsplit(L, "[[:space:]]")[[1]][1], FUN.VALUE = 'character')
}
words <- c("the quick", "brown dogs were", "lazier than quick foxes")
beforeSpace(words)
R> the quick brown dogs were lazier than quick foxes
"the" "brown" "lazier"
Run Code Online (Sandbox Code Playgroud)
并且让我知道是否有比grep(或我的功能beforeSpace)更好的方法来做到这一点.
the*_*ail 15
或者只是sub,归功于@flodel:
sub(" .*", "", words)
# and if the 'space' can also be a tab or other white-space:
sub("\\s.*","",words)
#[1] "the" "brown" "lazier"
Run Code Online (Sandbox Code Playgroud)
您可以使用qdap's beg2char(字符串以特定字符开头),如下所示:
x <- c("the quick", "brown dogs were", "lazier than quick foxes")
library(qdap)
beg2char(x)
## [1] "the" "brown" "lazier"
Run Code Online (Sandbox Code Playgroud)
使用stringi
library(stringi)
stri_extract_first(words, regex="\\w+")
#[1] "the" "brown" "lazier"
Run Code Online (Sandbox Code Playgroud)