实际上sprintf
对我不起作用,所以如果您不介意常见的依赖关系:
#reproducible example -- this happens with zip codes sometimes
X <- data.frame(A = c('10002','8540','BIRD'), stringsAsFactors=FALSE)
# X$A <- sprintf('%05s',X$A) didn't work for me
# Note in ?sprintf: 0: For numbers, pad to the field width with leading zeros.
# For characters, this zero-pads on some platforms and is ignored on others.
library('stringr')
X$A <- str_pad(X$A, width=5, side='left', pad='0')
X
# A
#1 10002
#2 08540
#3 0BIRD
或者,如果您更喜欢基本解决方案,则以下内容是等效的:
X$A <- ifelse(nchar(X$A) < 5, paste(c(rep("0",5-nchar(X$A)), X$A), collapse=""), X$A)
(请注意,这适用于长度为 4 或更少的字符串,而不仅仅是 4)