Ankit_Sharma
Ankit_Sharma

Reputation: 11

extracting character from character string as per certain conditions

Let's say

x = "R is so tough for SAS programmer"
y = "R why you so hard"

Now we have to find the word before 8th place and the first space (" ") encountered going right to left, i.e. backwards.

In case of x it would be the word "so"

In the case of y it would be "y"

How can I do this?

Upvotes: 1

Views: 42

Answers (2)

talat
talat

Reputation: 70336

Let's assume you have both strings in one vector:

x = c("R is so tough for SAS programmer", "R why you so hard")

Then, if I understand your question correctly, you can use a combination of substr to extract the first 7 characters of each string and then sub to extract the part after the last space:

sub(".*\\s", "", substr(x, 1, 7))
#[1] "so" "y" 

It may be safer to use

sub(".*\\s", "", trimws(substr(x, 1, 7), "right"))

which will cut off any whitespace on the right side of the vector resulting from substr. This ensures that the sub call won't accidentally match a space at the end of the string.

Upvotes: 2

akrun
akrun

Reputation: 887891

Here is another option with word and sub

library(stringr) 
word(sub("^(.{1,7}).*", "\\1", x), -1)
#[1] "so" "y" 

data

x <- c("R is so tough for SAS programmer", "R why you so hard")

Upvotes: 2

Related Questions