我有一个矩阵,基本上就像
100 2100
31000 230
31 9199
而且我希望每个数字都具有相同的大小,例如 100 --> 00100 或 9199 --> 09199。您对我有什么建议吗?
你可以使用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)))
您可以使用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)
我对相同的问题使用以下功能:
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