r用0和短划线格式化数字

时间:2017-09-11 05:57:57

标签: r number-formatting

我正在处理下面的数字

   12344
  233345
 7233433
 9343883
 3432837

我正在尝试格式化这些数字,使得它们在每三个数字后都具有相同的长度和短划线( - )。最终的预期结果如下所示。

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

非常感谢任何有关格式化这些数字的帮助。

5 个答案:

答案 0 :(得分:5)

尝试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"

使用的数据:

x <- scan(textConnection('12344
233345
7233433
9343883
3432837'))

答案 1 :(得分:3)

这是另一种解决方案,

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"

答案 2 :(得分:2)

我们可以使用stringrpurrr

# 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"

答案 3 :(得分:2)

以下是包含typescript-generated.jsbase R

sub选项
sprintf

答案 4 :(得分:1)

首先,您需要使用前导零来构建长度为7的字符串。我使用了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))

结果:

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

添加破折号应该很简单,现在:

paste0(substring(v1,1,1), "-", substring(v1,2,4), "-", substring(v1,5,7))