pad numeric column with leading zeros

前提是你 提交于 2019-12-02 00:50:03

问题


I've been looking into this for the past few hours. I have tried using sprintf but it changes the column to character. All I want to do is to have a fixed-width numeric column, padded with zeros.


回答1:


If you're willing to use a custom class, you can write a print method that does this. Make a data frame, and give it a custom class:

DF <- data.frame(a=letters[1:10], b=sample(c(1, 10, 100), 10, rep=T), c=sample(c(1, 10, 100), 10, rep=T))
class(DF) <- c("my_df", class(DF))

Write a print method that uses @BenBolker's formatting:

print.my_df <- function(x, ...) {
  num.cols <- sapply(x, is.numeric)
  x[num.cols] <- lapply(x[num.cols], sprintf, fmt="%04d")
  NextMethod()
}

And then:

DF

Produces:

   a    b    c
1  a 0100 0100
2  b 0010 0001
3  c 0001 0010
4  d 0001 0100
5  e 0001 0001
6  f 0001 0001
7  g 0001 0001
8  h 0001 0100
9  i 0001 0100
10 j 0001 0001

You can still use the data frame the same way since the numbers are only converted when they are printed.

> sum(DF$b)
[1] 118



回答2:


If you give more context we might be able to help you solve your ultimate (rather than proximal) problem, e.g. if you need output in this format but without quotation marks:

> cat(sprintf("%04d",5),"\n")
0005 
## or
> print(sprintf("%04d",5),quote=FALSE)
[1] 0005

write.csv(...,quote=FALSE) might be helpful too



来源:https://stackoverflow.com/questions/29635379/pad-numeric-column-with-leading-zeros

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!