0

I have a matrix which is basically like

100    2100  
31000  230  
31     9199

And I want every number to have the same size, like 100 --> 00100 or 9199 --> 09199. Do you have any suggestions for me?

Ernest Friedman-Hill
  • 80,601
  • 10
  • 150
  • 186

3 Answers3

2

You could use 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"

To automatically determine the minimum width, you can use this code:

minWidth <- max(nchar(formatC(numMx,format=frmt)))
digEmAll
  • 56,430
  • 9
  • 115
  • 140
2

You can use 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)
agstudy
  • 119,832
  • 17
  • 199
  • 261
0

I use the following function for same problems:

    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))
    }

Test:

    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
alexis_laz
  • 12,884
  • 4
  • 27
  • 37