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.
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.
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.
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With