0

I have a list and I want to replace the occurrence of one with count below

str_list <- c("2","1","2","1")
str_replace_all(str_list,"1",c("1:once","1:twice"))

gives output

[1] "2"       "1:twice" "2"       "1:twice"

but it should give

[1] "2"       "1:once" "2"       "1:twice"
mabrin
  • 11
  • 2

1 Answers1

1

You don't need regex here since this is an exact match. Try :

str_list[str_list == "1"] <- c("1:once","1:twice")
str_list
#[1] "2"       "1:once"  "2"       "1:twice"

The only precaution you need to take is make sure number of "1"s is same as number of replacement (c("1:once","1:twice")) otherwise it might give you unexpected results.

Ronak Shah
  • 377,200
  • 20
  • 156
  • 213