Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get characters before first space

Tags:

substring

regex

r

I am looking for a grep way to obtain the characters in a string prior to the first space.

I have hacked the following function, as i could not figure out how to do it using the grep type commands in R.

Could someone help with the 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 do let me know if there's a better way than grep (or my function, beforeSpace) to do this.

like image 425
ricardo Avatar asked Aug 25 '14 01:08

ricardo


People also ask

How do I extract text before first space?

You can quickly extract the text before space from the list only by using formula. Select a blank cell, and type this formula =LEFT(A1,(FIND(" ",A1,1)-1)) (A1 is the first cell of the list you want to extract text) , and press Enter button.

How do I see text before a character in Excel?

The TEXTBEFORE function in Excel is specially designed to return the text that occurs before a given character or substring (delimiter). In case the delimiter appears in the cell multiple times, the function can return text before a specific occurrence.


1 Answers

Or just sub, with credit to @flodel:

sub(" .*", "", words)
# and if the 'space' can also be a tab or other white-space:
sub("\\s.*","",words)
#[1] "the"    "brown"  "lazier"
like image 182
thelatemail Avatar answered Sep 30 '22 13:09

thelatemail