2

I want to add white space after three character in a string. I used the following code which works well. I wonder if there is any other simple way to accomplish the same task

library(stringi)
Test <- "3061660217"
paste(
    stri_sub(str = Test, from = 1, to = 3)
  , stri_sub(str = Test, from = 4)
  , sep = " "
  )

[1] "306 1660217"
Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
MYaseen208
  • 22,666
  • 37
  • 165
  • 309

1 Answers1

5

Using basic regex and stringr:

library(stringr)
str_replace(Test, pattern = "(.{3})(.*)", replacement = "\\1 \\2")

Output:

"306 1660217"

Same method works with base R as well:

gsub(Test, pattern = "(.{3})(.*)", replacement = "\\1 \\2")

Explanation:

  1. (.{3}) - find any 3 characters
  2. (.*) - find any character 0 or more times
  3. \\1 - backreferences (.{3})
  4. \\2 - backreferences (.*)
  5. The space between \\1 and \\2 is the space you want to add
bird
  • 2,938
  • 1
  • 6
  • 27