Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extracting characters before second to last whitespace [duplicate]

Tags:

string

r

I'm working in R and have the following:

"BOY MAN EL PASO ND 0023256000"

And I need to extract everything from the start to the second to last space. So:

"BOY MAN EL PASO"

I've tried:

substr(output$CUSTOMER, 1, sapply(strsplit(output$CUSTOMER, "\\s+"), tail, 2))

along with tons of variations of that line. I've found solutions to this same question in other posts but they want to extract characters between a specific character (like a slash) and when I try to adjust it I don't know how to reference a space.

Can someone help me with the R syntax on how to extract these characters?

like image 612
WantaghMomma Avatar asked Dec 13 '25 11:12

WantaghMomma


1 Answers

You can try sub with the regex pattern "^(.*)(\\s+\\S+){2}$"

> s <- "BOY MAN EL PASO ND 0023256000"

> sub("^(.*)(\\s+\\S+){2}$", "\\1", s)
[1] "BOY MAN EL PASO"
like image 131
ThomasIsCoding Avatar answered Dec 16 '25 12:12

ThomasIsCoding



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!