如何舍入到最接近的10或100或X?

如何解决如何舍入到最接近的10或100或X?

| 我正在写一个函数来绘制数据。我想为y轴
max
指定一个不错的整数,该整数大于数据集的最大值。 具体来说,我想执行以下功能的函数performs1ѭ:
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,但这不适用于任意舍入间隔。 在R中有更好的方法吗?     

解决方法

        如果只想舍入到最接近的10的幂,则只需定义:
roundUp <- function(x) 10^ceiling(log10(x))
当x是向量时,这实际上也适用:
> roundUp(c(0.0023,3.99,10,1003))
[1] 1e-02 1e+01 1e+01 1e+04
..但是如果要四舍五入为“ nice \”数字,则首先需要定义“ \ nice \”数字是什么。以下内容使我们可以将\“ nice \”定义为具有从1到10的良好基值的向量。默认设置为偶数加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是向量时,上述方法不起作用-现在太晚了:)
> 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的答案似乎是最合适的。我的版本允许您获取任何值并将其自动舍入为合理的“ nice”值。上面的“ nice”矢量的其他一些不错的选择是:
1:10,c(1,10),seq(1,0.1)
如果绘图中有一定范围的值,例如
[3996.225,40001.893]
,则自动方式应同时考虑范围的大小和数字的大小。而且正如Hadley所指出的那样,noted10ѭ函数可能正是您想要的。     ,        
plyr
库具有函数
round_any
,该函数非常通用,可以进行各种舍入。例如
library(plyr)
round_any(132.1,10)               # returns 130
round_any(132.1,f = ceiling)  # returns 140
round_any(132.1,f = ceiling)   # returns 135
    ,        如果R中的舍入函数为负,则它为digits参数赋予特殊含义。   四舍五入(x,数字= 0)      四舍五入为负数意味着要舍入为十的幂,因此例如round(x,digits = -2)会四舍五入到最接近的百位数。 这意味着类似于以下功能的功能非常接近您的要求。
foo <- function(x)
{
    round(x+5,-1)
}
输出如下所示
foo(4)
[1] 10
foo(6.1)
[1] 10
foo(30.1)
[1] 40
foo(100.1)
[1] 110
    ,        怎么样:
roundUp <- function(x,to=10)
{
  to*(x%/%to + as.logical(x%%to))
}
这使:
> roundUp(c(4,6.1,30.1,100.1))
[1]  10  10  40 110
> roundUp(4,5)
[1] 5
> roundUp(12,7)
[1] 14
    ,        如果在round()的数字参数中添加负数,R会将其四舍五入为10、100等的倍数。
    round(9,digits = -1) 
    [1] 10    
    round(89,digits = -1) 
    [1] 90
    round(89,digits = -2) 
    [1] 100
    ,         将ANY数字向上/向下舍入到ANY间隔 您可以使用模运算符
%%
轻松将数字四舍五入到指定的间隔。 功能:
round.choose <- function(x,roundTo,dir = 1) {
  if(dir == 1) {  ##ROUND UP
    x + (roundTo - x %% roundTo)
  } else {
    if(dir == 0) {  ##ROUND DOWN
      x - (x %% roundTo)
    }
  }
}
例子:
> round.choose(17,1)   #round 17 UP to the next 5th
[1] 20
> round.choose(17,0)   #round 17 DOWN to the next 5th
[1] 15
> round.choose(17,1)   #round 17 UP to the next even number
[1] 18
> round.choose(17,0)   #round 17 DOWN to the next even number
[1] 16
怎么运行的: 模运算符
%%
确定将第一个数除以2的余数。在您感兴趣的数字上添加或减去此间隔实际上可以将数字“四舍五入”到您选择的间隔。
> 7 + (5 - 7 %% 5)       #round UP to the nearest 5
[1] 10
> 7 + (10 - 7 %% 10)     #round UP to the nearest 10
[1] 10
> 7 + (2 - 7 %% 2)       #round UP to the nearest even number
[1] 8
> 7 + (100 - 7 %% 100)   #round UP to the nearest 100
[1] 100
> 7 + (4 - 7 %% 4)       #round UP to the nearest interval of 4
[1] 8
> 7 + (4.5 - 7 %% 4.5)   #round UP to the nearest interval of 4.5
[1] 9

> 7 - (7 %% 5)           #round DOWN to the nearest 5
[1] 5
> 7 - (7 %% 10)          #round DOWN to the nearest 10
[1] 0
> 7 - (7 %% 2)           #round DOWN to the nearest even number
[1] 6
更新: 方便的2参数版本:
rounder <- function(x,y) {
  if(y >= 0) { x + (y - x %% y)}
  else { x - (x %% abs(y))}
}
正ѭ25值
roundUp
,而负
y
roundDown
 # rounder(7,-4.5) = 4.5,while rounder(7,4.5) = 9.
要么.... 根据标准舍入规则自动向上或向下舍入的函数:
Round <- function(x,y) {
  if((y - x %% y) <= x %% y) { x + (y - x %% y)}
  else { x - (x %% y)}
}
如果
x
的值是舍入值
y
的后续实例之间的中间值
>
,则自动舍入:
# Round(1.3,1) = 1 while Round(1.6,1) = 2
# Round(1.024,0.05) = 1 while Round(1.03,0.05) = 1.05
    ,        关于四舍五入到任意数字的倍数,例如10,这是詹姆斯答案的一种简单替代方案。 它适用于任何四舍五入的实数(
from
)和任何四舍五入的实数(
to
):
> RoundUp <- function(from,to) ceiling(from/to)*to
例:
> RoundUp(-11,10)
[1] -10
> RoundUp(-0.1,10)
[1] 0
> RoundUp(0,10)
[1] 0
> RoundUp(8.9,10)
[1] 10
> RoundUp(135,10)
[1] 140

> RoundUp(from=c(1.3,2.4,5.6),to=1.1)  
[1] 2.2 3.3 6.6
    ,        我认为您的代码只要稍加修改就可以很好地工作:
foo <- function(x,round=10) ceiling(max(x+10^-9)/round + 1/round)*round
您的示例运行:
> foo(4,round=1) == 5
[1] TRUE
> foo(6.1) == 10            #maybe 7 would be better
[1] TRUE
> foo(6.1,round=1) == 7    # you got 7
[1] TRUE
> foo(30.1) == 40
[1] TRUE
> foo(100.1) == 110
[1] TRUE
> # ALL in one:
> foo(c(4,100))
[1] 110
> foo(c(4,100),round=10)
[1] 110
> foo(c(4,round=2.3)
[1] 101.2
我通过两种方式更改了您的功能: 添加第二个参数(对于您指定的X) 如果您想要更大的数字,请在
max(x)
中添加一个较小的值(
=1e-09
,随时可以修改!)。     ,        如果您始终想将数字四舍五入到最接近的X,可以使用
ceiling
函数:
#Round 354 up to the nearest 100:
> X=100
> ceiling(354/X)*X
[1] 400

#Round 47 up to the nearest 30:
> Y=30
> ceiling(47/Y)*Y
[1] 60
同样,如果您始终想舍入,请使用
floor
函数。如果只想向上或向下舍入到最接近的Z,请改用
round
> Z=5
> round(367.8/Z)*Z
[1] 370
> round(367.2/Z)*Z
[1] 365
    ,        您会发现汤米答案的升级版本,其中考虑了以下几种情况: 在上下限之间选择 考虑负值和零值 如果您希望函数对小数和大数进行舍入,则可以使用两个不同的小数位数。示例:4将四舍五入为0,而400将四舍五入为400。 下面的代码:
round.up.nice <- function(x,lower_bound = TRUE,nice_small=c(0,nice_big=c(1,3,7,9,10)) {
  if (abs(x) > 100) {
    nice = nice_big
  } else {
    nice = nice_small
  }
  if (lower_bound == TRUE) {
    if (x > 0) {
      return(10^floor(log10(x)) * nice[[max(which(x >= 10^floor(log10(x)) * nice))[[1]]]])
    } else if (x < 0) {
      return(- 10^floor(log10(-x)) * nice[[min(which(-x <= 10^floor(log10(-x)) * nice))[[1]]]])
    } else {
      return(0)
    }
  } else {
    if (x > 0) {
      return(10^floor(log10(x)) * nice[[min(which(x <= 10^floor(log10(x)) * nice))[[1]]]])
    } else if (x < 0) {
      return(- 10^floor(log10(-x)) * nice[[max(which(-x >= 10^floor(log10(-x)) * nice))[[1]]]])
    } else {
      return(0)
    }
  }
}
    ,        我尝试了此操作,没有使用任何外部库或神秘功能,并且可以正常工作! 希望它可以帮助某人。
ceil <- function(val,multiple){
  div = val/multiple
  int_div = as.integer(div)
  return (int_div * multiple + ceiling(div - int_div) * multiple)
}

> ceil(2.1,2.2)
[1] 2.2
> ceil(3,2.2)
[1] 4.4
> ceil(5,10)
[1] 10
> ceil(0,10)
[1] 0
    

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-