How to remove anything that starts with specific character (@) in various locations in string in R?

Viewed 715

I have a column that contains multiple tweets:

ID | Tweet
1    @ChipotleTweets @ChipotleTweets Becky is very nice
2    Happy Halloween! I now look forward to $3 booritos at @ChipotleTweets
3    Considering walking to @.ChipotleTweets in my llama onesie.

The goal is to remove the '@___' and anything that is after @ - but not the text spaced outside that string.

Playing around this code currently to detect '@' but I am not picking up anything if it's not in the first position of the sentence

tweet_pattern <- " @\\w+"

Customer <- Customer %>% 
           clean_Tweet = ifelse(str_detect(text, tweet_pattern), 
                                str_remove(text, tweet_pattern), 
                                NA_character_))

Desired output:

ID | Tweet                                                                  | cleaned_tweet 
1    @ChipotleTweets @ChipotleTweets Becky is very nice                       Becky is very nice
2    Happy Halloween! I now look forward to $3 booritos at @ChipotleTweets    Happy Halloween! I now look forward to $3 booritos at
3    Considering walking to @.ChipotleTweets in my llama onesie.              Considering walking to in my llama onesie.
1 Answers

We may change the pattern to match zero or more space (\\s*) followed by @ and one or more non-white space (\\S+) in str_remove_all to remove those substring

library(stringr)
library(dplyr)
Customer %>%
     mutate(Cleaned_Tweet = str_remove_all(Tweet, "\\s*@\\S+"))

-output

 ID                                                                 Tweet                                         Cleaned_Tweet
1  1                    @ChipotleTweets @ChipotleTweets Becky is very nice                                    Becky is very nice
2  2 Happy Halloween! I now look forward to $3 booritos at @ChipotleTweets Happy Halloween! I now look forward to $3 booritos at
3  3           Considering walking to @.ChipotleTweets in my llama onesie.            Considering walking to in my llama onesie.

NOTE: str_remove just removes the first instance of match i.e. if there are more than one match in a single string, it skips the others and matches only the first. We need str_remove_all for removing all instances of matching patterns.

data

Customer <- structure(list(ID = 1:3, Tweet = c("@ChipotleTweets @ChipotleTweets Becky is very nice", 
"Happy Halloween! I now look forward to $3 booritos at @ChipotleTweets", 
"Considering walking to @.ChipotleTweets in my llama onesie."
)), class = "data.frame", row.names = c(NA, -3L))
Related