一个矩阵中所有数字的长度相同

时间:2013-10-12 11:48:39

标签: r matrix

我有一个基本上像

的矩阵
100    2100  
31000  230  
31     9199

我希望每个数字都有相同的大小,比如100 - > 00100或9199 - > 09199.你对我有什么建议吗?

3 个答案:

答案 0 :(得分:2)

您可以使用formatC

numMx <- matrix(c(100,2100,31000,230,31,9199),nrow=3,byrow=T)

frmt <- "d"   # d --> numbers formatted as integers
minWidth <- 5 # minimum characters length of each number e.g. 42 --> "00042"

chMx <- formatC(numMx, width = minWidth, format = frmt, flag = "0")

# > chMx
#      [,1]    [,2]   
# [1,] "00100" "02100"
# [2,] "31000" "00230"
# [3,] "00031" "09199"

要自动确定最小宽度,您可以使用以下代码:

minWidth <- max(nchar(formatC(numMx,format=frmt)))

答案 1 :(得分:2)

您可以使用sprintf

dat <- read.table(text='100    2100  
31000  230  
31     9199')

max.len <- max(apply(dat,2,function(x)
           nchar(as.character(x))))

matrix(sprintf(paste0("%0",max.len,"d"), unlist(dat)),
          ncol=2)

答案 2 :(得分:0)

我使用以下函数来解决同样的问题:

    add0 <- function(x, len) #x = number to add 0 ; len = the wanted length of the number
    {
     x.len <- length(unlist(strsplit(as.character(x), split = "")))
     ifelse(x.len < len, paste(paste(rep(0, len - x.len), collapse = ""), x, sep = ""), as.character(x))
    }

测试:

    mat <- matrix(sample(1:25, 25), 5, 5) #random matrix

    apply(mat, c(1,2), add0, len = max(nchar(as.character(mat)))) #change whole matrix using maximum "length" of its values