如何四舍五入到最接近的 10(或 100 或 X)? [英] How to round up to the nearest 10 (or 100 or X)?

查看:67
本文介绍了如何四舍五入到最接近的 10(或 100 或 X)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个函数来绘制数据.我想为 y 轴 max 指定一个大于数据集最大值的整数.

I am writing a function to plot data. I would like to specify a nice round number for the y-axis max that is greater than the max of the dataset.

具体来说,我想要一个函数 foo 来执行以下操作:

Specifically, I would like a function foo that performs the following:

foo(4) == 5
foo(6.1) == 10 #maybe 7 would be better
foo(30.1) == 40
foo(100.1) == 110 

我已经达到了

foo <- function(x) ceiling(max(x)/10)*10

四舍五入到最接近的 10,但这不适用于任意四舍五入间隔.

for rounding to the nearest 10, but this does not work for arbitrary rounding intervals.

在 R 中有更好的方法吗?

Is there a better way to do this in R?

推荐答案

如果你只想四舍五入到最接近的 10 的幂,那么只需定义:

If you just want to round up to the nearest power of 10, then just define:

roundUp <- function(x) 10^ceiling(log10(x))

当 x 是向量时,这实际上也有效:

This actually also works when x is a vector:

> roundUp(c(0.0023, 3.99, 10, 1003))
[1] 1e-02 1e+01 1e+01 1e+04

..但是如果你想四舍五入到一个好"的数字,你首先需要定义一个好"的数字是什么.下面让我们将nice"定义为一个基值从 1 到 10 的向量.默认设置为偶数加 5.

..but if you want to round to a "nice" number, you first need to define what a "nice" number is. The following lets us define "nice" as a vector with nice base values from 1 to 10. The default is set to the even numbers plus 5.

roundUpNice <- function(x, nice=c(1,2,4,5,6,8,10)) {
    if(length(x) != 1) stop("'x' must be of length 1")
    10^floor(log10(x)) * nice[[which(x <= 10^floor(log10(x)) * nice)[[1]]]]
}

当 x 是向量时,上面的方法不起作用 - 现在晚上太晚了 :)

The above doesn't work when x is a vector - too late in the evening right now :)

> roundUpNice(0.0322)
[1] 0.04
> roundUpNice(3.22)
[1] 4
> roundUpNice(32.2)
[1] 40
> roundUpNice(42.2)
[1] 50
> roundUpNice(422.2)
[1] 500

[]

如果问题是如何舍入到指定的最近值(如 10 或 100),那么 James answer 似乎最合适的.我的版本允许您采用任何值并自动将其四舍五入为合理的不错"值.上面nice"向量的其他一些不错的选择是:1:10, c(1,5,10), seq(1, 10, 0.1)

If the question is how to round to a specified nearest value (like 10 or 100), then James answer seems most appropriate. My version lets you take any value and automatically round it to a reasonably "nice" value. Some other good choices of the "nice" vector above are: 1:10, c(1,5,10), seq(1, 10, 0.1)

如果您的图中有一系列值,例如 [3996.225, 40001.893] 那么自动方式应该同时考虑范围的大小和数字的大小.正如 指出的那样Hadleypretty() 函数可能正是您想要的.

If you have a range of values in your plot, for example [3996.225, 40001.893] then the automatic way should take into account both the size of the range and the magnitude of the numbers. And as noted by Hadley, the pretty() function might be what you want.

这篇关于如何四舍五入到最接近的 10(或 100 或 X)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆