replace multiple values in a string

Rich Pauloo

What's the most syntactically simple way to replace multiple values in a string expression?

Let's say I have:

string <- "1 2 3 4 5 6 7 8 9"

And I want to replace all 1's, 2's, 3's, and 4's with '0'. I can use stringr::str_replace():

string %>% 
  str_replace("1", "0") %>% 
  str_replace("2", "0") %>% 
  str_replace("3", "0") %>% 
  str_replace("4", "0") 

What is a better way to do this kind of operation?


EDIT:

Joran's answer: use str_replace_all()

str_replace_all(string = string,pattern = "[1234]",replacement = "0")

user2738526's answer: use gsub()

gsub("[1-4]","0",string)
akrun

A simple option would be chartr

chartr('1234', '0000', string)
#[1] "0 0 0 0 5 6 7 8 9"

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related