GarlicSTAT
GarlicSTAT

Reputation: 243

Remove specific letter in a string in R

I have strings like this:
*the string is in class "factor"

string1= "applepearbananao234range"
string2= "appleorangewater342melon"
string3= "applepearwaterme436lonkl"
s_df=rbind(string1,string2,string3)
s_df=data.frame(s_df)

I would like to remove the word apple (which is the first 5 letters) and the numbers at position 16 to 18 in the data frame s_df .

Edit: the codes and the question.

Upvotes: 0

Views: 88

Answers (2)

akrun
akrun

Reputation: 887891

We can use str_replace

library(stringr)
str_replace_all(string1, "apple|23", "")
#[1] "pearbananao4range"

Upvotes: 1

Ronak Shah
Ronak Shah

Reputation: 389275

Use gsub

gsub("apple|23", "", string1)
#[1] "pearbananaorange"

Or with str_remove_all

stringr::str_remove_all(string1, "apple|23")

For the updated data, we can do

gsub("^apple|\\d+", "", s_df$s_df)
#[1] "pearbananaorange" "orangewatermelon" "pearwatermelonkl"

Upvotes: 2

Related Questions