1

I have a string Vector including numbers like this:

x <- c("abc122", "73dj", "lo7833ll")

x
[1] "abc122"   "73dj"     "lo7833ll"

I want to Change the numbers of the x Vector and replace them with numbers I have stored in another Vector:

right_numbers <- c(500, 700, 23)
> right_numbers
[1] 500 700  23

How can I do this even if the numbers are in different positions in the string(some are at the beginning, some at the end..)?

This is how the x Vector should look like after the changes:

> x
[1] "abc500"   "700dj"     "lo23ll"
Sotos
  • 51,121
  • 6
  • 32
  • 66
  • `sapply(seq_along(x), function(i) {sub("[0-9]+", right_numbers[i], x[i])})` – GKi Sep 03 '19 at 14:24
  • Some related & possible helpful ideas [here](https://stackoverflow.com/q/19424709/5325862), [here](https://stackoverflow.com/q/29403080/5325862), [here](https://stackoverflow.com/q/26171318/5325862) – camille Sep 03 '19 at 15:30

2 Answers2

2

A vectorized solution with stringr -

str_replace(x, "[0-9]+", as.character(right_numbers))

[1] "abc500" "700dj"  "lo23ll"

Possibly a more efficient version with stringi package, thanks to @sindri_baldur -

stri_replace_first_regex(x, '[0-9]+', right_numbers)

[1] "abc500" "700dj"  "lo23ll"
Shree
  • 10,835
  • 1
  • 14
  • 36
  • Or straight with (more efficient) `stringi`: `stri_replace_first_regex(x, '[0-9]+', right_numbers)` – s_baldur Sep 03 '19 at 14:34
  • @sindri_baldur Thanks! I am not familiar with `stringi` package but I'll add this to the answer with your name. – Shree Sep 03 '19 at 14:40
  • `stringr` functions are shorter and simpler wrappers for `stringi` functions. – s_baldur Sep 03 '19 at 15:06
1

Here is an idea,

mapply(function(i, y)gsub('[0-9]+', y, i), x, right_numbers)
#  abc122     73dj lo7833ll 
#"abc500"  "700dj" "lo23ll" 
Sotos
  • 51,121
  • 6
  • 32
  • 66