在 R 中,您将如何编写包装函数或类来将数字格式化为百分比、货币等? [英] How would you write a wrapper function or class to format numbers as percent, currency, etc. in R?
问题描述
在上一个问题中,我询问了基 R 中是否存在方便的包装器来将数字格式化为百分比.
In a previous question, I asked whether whether a convenient wrapper exists inside base R to format numbers as percentages.
这引起了三个回应:
- 可能不会.
- 这样的包装器太窄而无用.用户最好学习如何使用现有工具,例如
sprintf
,它们可以高度灵活地格式化数字. - 无论如何,这样的包装器是有问题的,因为您无法对对象执行计算.
- Probably not.
- Such a wrapper would be too narrow to be useful. It is better that useRs learn how to use existing tools, such as
sprintf
, which can format numbers in a highly flexible way. - Such a wrapper is problematic, anyway, since you lose the ability to perform calculations on the object.
不过,在我看来,sprintf
函数对于 R 初学者来说有点过于模糊,无法学习(除非他们来自 C 背景).也许更好的解决方案是修改 format
或 prettyNum
以提供添加前缀和后缀的选项,这样您就可以轻松创建百分比、货币、度数等.
Still, in my view the sprintf
function is just a little bit too obfuscated for the R beginner to learn (except if they come from a C background). Perhaps a better solution is to modify format
or prettyNum
to have options for adding prefixes and suffixes, so you could easily create percents, currencies, degrees, etc.
问题:
您将如何设计一个函数、类或函数集,以优雅地将数字格式化为百分比、货币、度数等?
How would you design a function, class or set of functions to elegantly deal with formatting numbers as percentages, currencies, degrees, etc?
推荐答案
我可能会让事情变得非常简单.format()
通常可用于大多数基本的格式化需求.我会用一个允许任意 prefix
和 suffix
字符串的简单包装器来扩展它.这是一个简单的版本:
I would probably keep things very simple. format()
is generally useful for most basic formatting needs. I would extend that with a simple wrapper that allowed arbitrary prefix
and suffix
strings. Here is a simple version:
formatVal <- function(x, prefix = "", suffix = "", sep = "", collapse = NULL,
...) {
x <- format(x, ...)
x <- paste(prefix, x, suffix, sep = sep, collapse = collapse)
x
}
如果我真的这样做,我可能不会在 formatVal()
的定义中使用 collapse
参数,而是从 中处理它...
,但为了说明,我保持上述功能简单.
If I were doing this for real, I would probably not have the collapse
argument in the definition of formatVal()
, but instead process it out of ...
, but for illustration I kept the above function simple.
使用:
set.seed(1)
m <- runif(5)
一些简单的用法示例
> formatVal(m*100, suffix = "%")
[1] "26.55087%" "37.21239%" "57.28534%" "90.82078%" "20.16819%"
> formatVal(m*100, suffix = "%", digits = 2)
[1] "27%" "37%" "57%" "91%" "20%"
> formatVal(m*100, suffix = "%", digits = 2, nsmall = 2)
[1] "26.55%" "37.21%" "57.29%" "90.82%" "20.17%"
> formatVal(m, prefix = "£")
[1] "£0.2655087" "£0.3721239" "£0.5728534" "£0.9082078" "£0.2016819"
> formatVal(m, prefix = "£", digits = 1)
[1] "£0.3" "£0.4" "£0.6" "£0.9" "£0.2"
> formatVal(m, prefix = "£", digits = 1, nsmall = 2)
[1] "£0.27" "£0.37" "£0.57" "£0.91" "£0.20"
这篇关于在 R 中,您将如何编写包装函数或类来将数字格式化为百分比、货币等?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!