Get characters before first space

I am looking for a grep way to get characters in a string before the first space.

I hacked the following function because I could not figure out how to do this using commands like grep in R

Can anyone help with grep solution - if there is one ...

 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" 

And let me know if this is a better way than grep (or my function, beforeSpace ).

+5
source share
4 answers

Or just sub , given @flodel:

 sub(" .*", "", words) # and if the 'space' can also be a tab or other white-space: sub("\\s.*","",words) #[1] "the" "brown" "lazier" 
+8
source

You can use qdap beg2char (beginning of line for a specific character) as follows:

 x <- c("the quick", "brown dogs were", "lazier than quick foxes") library(qdap) beg2char(x) ## [1] "the" "brown" "lazier" 
+3
source

Using stringi

 library(stringi) stri_extract_first(words, regex="\\w+") #[1] "the" "brown" "lazier" 
+3
source

You can use the word function from the stringr package. Nothing but the vector x , it returns the first word in the string, where the words are separated by a space.

 > x <- c("the quick", "brown dogs were", "lazier than quick foxes") > library(stringr) > word(x) # [1] "the" "brown" "lazier" 

And to match the output from your beforeSpace function, we can use setNames

 > setNames(word(x), x) # the quick brown dogs were lazier than quick foxes # "the" "brown" "lazier" 

Another option is strsplit with sapply instead of vapply

 > sapply(strsplit(x, " "), "[", 1) # [1] "the" "brown" "lazier" 
+1
source

Source: https://habr.com/ru/post/1201049/


All Articles