thibaultdej
thibaultdej

Reputation: 21

Add a space every two characters in R

I have phone numbers in the form of:

0123456789

and I'd like to make them look like

01 23 45 67 89

So far, adding a zero is no big deal with the paste0 function, but I'd like something a bit simpler than a long chain of nested paste0 and substr. Something might be possible with a regex reading every two digits, but I don't see how to make it happen.

Upvotes: 0

Views: 6047

Answers (3)

Roland
Roland

Reputation: 132999

Without regex:

x <- "0123456789"
formatC(as.numeric(x), big.mark = " ", big.interval = 2, 
        format = "d", flag = "0", width = nchar(x))
#[1] "01 23 45 67 89"

Upvotes: 4

amatsuo_net
amatsuo_net

Reputation: 2448

This is a bit package-heavy solution than Tim's but you can do something like this with dplyr and stringr

library(dplyr)
library(stringr)
original_string %>% 
  paste0(0, .) %>% # add 0 to the head
  str_replace_all("(.{2})", "\\1 ") %>% # insert spaces after every to digits
  str_trim() # remove the space in the end if it's there

Upvotes: 2

Tim Biegeleisen
Tim Biegeleisen

Reputation: 522797

You can replace the regex expression (.{2}) with \\1. Note that there is also a trailing whitespace problem, since we don't want to add an extraneous extra space at the end of the string for inputs with an even quantity of digits. To handle this, we can just remove trailing whitespace from our replaced string.

x <- '0123456789'
y <- sub("\\s+$", "", gsub('(.{2})', '\\1 ', x))
y
[1] "01 23 45 67 89"

Demo

Upvotes: 5

Related Questions