Remove first two words from string

Viewed 1470

I have a text:

s="Daniel S Hi What are you doing today"
s1="Mary G I am occupied with some work today"
s2="Cindy U Hey you guys are joining today's conference"

I want to remove first two words from all of the text, I have just given 3 text but there are more thousand text like this, first two words pattern going to be same, first word is some name and second word is a single alphabet.

Expected output:

s="Hi What are you doing today"
s1="I am occupied with some work today"
s2="Hey you guys are joining today's conference"
3 Answers

You can remove first two words from each text using regex.

x <- c("Daniel S Hi What are you doing today", "Mary G I am occupied with some work today", "Cindy U Hey you guys are joining today's conference")
sub('^\\w+\\s\\w+\\s', '', x)

#[1] "Hi What are you doing today"                 "I am occupied with some work today"         
#[3] "Hey you guys are joining today's conference"

Using base R:

str
[1] "Daniel S Hi What are you doing today"               
[2] "Mary G I am occupied with some work today"          
[3] "Cindy U Hey you guys are joining today's conference"
sapply(sapply(strsplit(str, split = ' '), function(x) x[3:length(x)]), paste, collapse = ' ')
[1] "Hi What are you doing today"                 "I am occupied with some work today"         
[3] "Hey you guys are joining today's conference"

Base R solution:

list2env(Map(function(x){gsub("\\w+\\s*\\w+\\s*(.*)", "\\1", x)}, 
    mget(ls(pattern = "^s.*"))), .GlobalEnv)
Related