如何在R中将数字格式化为百分比?

编程入门 行业动态 更新时间:2024-10-25 18:35:13
本文介绍了如何在R中将数字格式化为百分比?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

例如,display 是一个用来将R作为newby来使用的东西, c $ c> 0.12345 为 12.345%。对此我有一些解决方法,但是这些都不是友好的。例如:

set.seed(1)m < - runif(5) paste(round(100 * m,2),%,sep =) [1]26.55%37.21%57.29%90.82%20.17% sprintf(%1.2f %%,100 * m) [1]26.55%37.21%57.29%90.82%20.17%

问题:是否有一个基本的R函数可以做到这一点?另外,是否有一个广泛使用的包提供了一个方便的包装?

尽管在?format ,?formatC 和?prettyNum ,我还没有找到一个适当方便的包装在基础R. ??percent没有产生任何有用的东西。 库(SOS); findFn(格式百分比)返回1250个匹配 - 所以再次没用。 ggplot2 有一个函数 percent ,但是这不能控制舍入的准确性。

这几天有一个解决方案在 中 project/web/packages/scales/index.html> scale 包,如krlmlr的答案中所述。使用它,而不是我的手滚解决方案。

试试像

percent < - function(x,digits = 2,format =f,...){ paste0(formatC(100 * x,format =格式,数字=数字,...),%)}

例如,

x <-c(-1,0,0.1,0.555555,1,100)%(x)

(如果您愿意,请将格式从 f到g。)

One of the things that used to perplex me as a newby to R was how to format a number as a percentage for printing.

For example, display 0.12345 as 12.345%. I have a number of workarounds for this, but none of these seem to be "newby friendly". For example:

set.seed(1) m <- runif(5) paste(round(100*m, 2), "%", sep="") [1] "26.55%" "37.21%" "57.29%" "90.82%" "20.17%" sprintf("%1.2f%%", 100*m) [1] "26.55%" "37.21%" "57.29%" "90.82%" "20.17%"

Question: Is there a base R function to do this? Alternatively, is there a widely used package that provides a convenient wrapper?

Despite searching for something like this in ?format, ?formatC and ?prettyNum, I have yet to find a suitably convenient wrapper in base R. ??"percent" didn't yield anything useful. library(sos); findFn("format percent") returns 1250 hits - so again not useful. ggplot2 has a function percent but this gives no control over rounding accuracy.

解决方案

An update, several years later:

These days there is a percent function in the scales package, as documented in krlmlr's answer. Use that instead of my hand-rolled solution.

Try something like

percent <- function(x, digits = 2, format = "f", ...) { paste0(formatC(100 * x, format = format, digits = digits, ...), "%") }

With usage, e.g.,

x <- c(-1, 0, 0.1, 0.555555, 1, 100) percent(x)

(If you prefer, change the format from "f" to "g".)

更多推荐

如何在R中将数字格式化为百分比?

本文发布于:2023-10-30 08:03:39,感谢您对本站的认可!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:百分比   中将   格式   数字   如何在

发布评论

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

>www.elefans.com

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