1

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?

talat
  • 68,970
  • 21
  • 126
  • 157
  • 1
    Please provide us with a reproducible example: https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example – deca Sep 14 '17 at 06:43
  • @Martin, did you read the question? It includes an example with expected output – talat Sep 14 '17 at 06:50

2 Answers2

2

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.

talat
  • 68,970
  • 21
  • 126
  • 157
2

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")
akrun
  • 874,273
  • 37
  • 540
  • 662