2

I am dealing with numbers like this below

   12344
  233345
 7233433
 9343883
 3432837

I am trying to format these number such that they all are of same length and dash (-) after every three numbers. The final expected results should like this below.

  0-012-344
  0-233-345
  7-233-433
  9-343-883
  3-432-837

Any help on formatting these numbers this way is much appreciated.

Science11
  • 788
  • 1
  • 8
  • 24

5 Answers5

5

Try formatC:

formatC(x, width = 7, format = "d", flag = "0", big.mark = '-')
# [1] "0-012-344" "0-233-345" "7-233-433" "9-343-883" "3-432-837"

The data used:

x <- scan(textConnection('12344
233345
7233433
9343883
3432837'))
mt1022
  • 16,834
  • 5
  • 48
  • 71
3

Here is another solution,

my_format <- function(num){
x <- sprintf("%07d", num)
paste0(substr(x, 1,1), "-",
    substr(x, 2,4), "-",
    substr(x, 5,7))
}

nums <-  c(12344,233345,7233433,9343883,3432837)
my_format(nums)

# gives
[1] "0-012-344" "0-233-345" "7-233-433" "9-343-883" "3-432-837"
Remko Duursma
  • 2,741
  • 17
  • 24
2

We can use stringr and purrr.

# Data
numbers <- c("12344", "233345", "7233433", "9343883", "3432837")

# Load package
library(stringr)
library(purrr)

# A function to add dash line
trans_num <- function(number){
  part1 <- str_sub(number, start = 1, end = 1)
  part2 <- str_sub(number, start = 2, end = 4)
  part3 <- str_sub(number, start = 5)
  return(paste(part1, part2, part3, sep = "-"))
}

numbers %>%
  str_pad(width = 7, pad = "0") %>%
  map_chr(trans_num)
[1] "0-012-344" "0-233-345" "7-233-433" "9-343-883" "3-432-837"
www
  • 38,575
  • 12
  • 48
  • 84
2

Here is a base R option with sub and sprintf

sub("(.)(.{3})", '\\1-\\2-', sprintf("%07d", x))
#[1] "0-012-344" "0-233-345" "7-233-433" "9-343-883" "3-432-837"
akrun
  • 874,273
  • 37
  • 540
  • 662
1

First you'll need to build your strings of length seven with leading zeroes. I used this:

strReverse <- function(x)
    sapply(lapply(strsplit(x, NULL), rev), paste, collapse="")

v = as.character(read.table(text = "   12344
  233345
 7233433
 9343883
 3432837", header = FALSE)[,1])

v1 = strReverse( substring(paste0(strReverse(v), "0000"), 1, 7))

Result:

> v1
[1] "0012344" "0233345" "7233433" "9343883" "3432837"

Adding dashes should be straightforward, now:

paste0(substring(v1,1,1), "-", substring(v1,2,4), "-", substring(v1,5,7))
lebelinoz
  • 4,890
  • 10
  • 33
  • 56