前缀零到列表

时间:2016-03-10 14:20:01

标签: r

我有数字列表:

> list1 <- c(1:10, 100, 1000)
> list1
 [1]    1    2    3    4    5    6    7    8    9   10  100 1000

我希望使用零来为数字添加前缀,列表中的最大数字。我已经完成了这个功能:

prefix.zeros  <- function(VECTOR){
  max_length   <- nchar(max(VECTOR))
  retval       <- vector()

  for (i in 1:length(VECTOR)){
    prefix     <- vector()
    cur_length <- nchar(VECTOR[i])

    for(j in cur_length:(max_length-1)){
      if (cur_length == max_length){
        prefix <- ""
      }
      else if (cur_length < max_length){
        prefix <- c(prefix,"0")
      }
    }
    retval <- c(retval, paste0(paste0(prefix, collapse = ""), VECTOR[i], collapse = ""))
  }
  retval
}

哪种方法正常:

> prefix.zeros(list1)
 [1] "0001" "0002" "0003" "0004" "0005" "0006" "0007" "0008" "0009" "0010" "0100"
[12] "1000"

但是我想知道是否有更优雅(R-way)的方式?

1 个答案:

答案 0 :(得分:4)

sprintf(paste0("%0", max(nchar(list1)), "d"), list1)
# [1] "0001" "0002" "0003" "0004" "0005" "0006" "0007" "0008" "0009" "0010" "0100" "1000"