0

I am trying to replace multiple patterns in a string (column). The issue I'm having is with using str_replace. I list the string, the pattern to replace, and the replacement and it works with 1, but I can't seem to figure out how to replace multiple patterns (3) in the string. Each intended pattern has a specific replacement.

The three patterns I'm replacing start with the letter P, N, or G and I want to replace them with Positive, Negative, General.

What I have so far is:

spreadsheet.dat1<-spreadsheet.dat %>%
  mutate(domain=str_replace(column, "^P.*", "Positive"))
spreadsheet.dat2<-spreadsheet.dat1 %>%
  mutate(domain=str_replace(column, "^N.*", "Negative"))
spreadsheet.dat3<-spreadsheet.dat2 %>%
  mutate(domain=str_replace(column, "^P.*", "General"))

What I was hoping is that it would cumulatively add into the new column, domain, with the positive, negative, general all replaced by spreadsheet.dat3, but instead it only replaces w the current function.

Any tips?

1 Answer 1

2

It would help if you gave a small example dataset and then an example of what you'd like it turned into. I think what you're looking for is

spreadsheet.dat1<-spreadsheet.dat %>%
mutate(domain=case_when(str_starts(column, "P") ~ "Positive",
str_starts(column, "N") ~ "Negative",
str_starts(column, "G") ~ "General",
TRUE ~ NA_character_))
Sign up to request clarification or add additional context in comments.

1 Comment

Since it's on a virtual desktop I can't copy paste but essentially the original column has various data named P01, P02, P03, etc, N01, N02, N03, etc, G01, G02, G03 etc and I wanted to change these all to Positive, Negative, General respectively. What you posted is exactly what I was looking for (it worked)! Thank you so much!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.