用前导零填充数字列

编程入门 行业动态 更新时间:2024-10-24 16:31:09
本文介绍了用前导零填充数字列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

过去几个小时我一直在研究这个问题.我曾尝试使用 sprintf 但它将列更改为字符.我想要做的就是有一个固定宽度的数字列,用零填充.

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.

推荐答案

如果您愿意使用自定义类,您可以编写执行此操作的打印方法.制作一个数据框,并给它一个自定义类:

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

编写一个使用@BenBolker 格式的打印方法:

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

然后:

DF

产生:

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

更多推荐

用前导零填充数字列

本文发布于:2023-08-05 21:21:17,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1308126.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:前导   数字

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!