Reputation: 23898
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"
Upvotes: 3
Views: 2793
Reputation: 3294
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:
(.{3})
- find any 3 characters(.*)
- find any character 0 or more times\\1
- backreferences (.{3})
\\2
- backreferences (.*)
\\1
and \\2
is the space you want to addUpvotes: 7