如何在 R 中舍入为 1、1.5、2 等而不是 1、2 或 1.1、1.2、1.3? [英] How do I round to 1, 1.5, 2 etc instead of 1, 2 or 1.1, 1.2, 1.3 in R?
本文介绍了如何在 R 中舍入为 1、1.5、2 等而不是 1、2 或 1.1、1.2、1.3?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想将数字四舍五入到最接近的半数或整数.所以我想把 4.2 舍入到 4、4.3 到 4.5 和 4.8 到 5.我用舍入选项尝试了一些东西:
I want to round numbers to the closest half or whole number. So I want to round 4.2 to 4, 4.3 to 4.5 and 4.8 to 5. I tried a few things with the round option:
> round(4.34,1)
[1] 4.3
> round(4.34)
[1] 4
> round(4.34,0.5)
[1] 4.3
> round(4.34,2)
[1] 4.34
所以我只知道如何增加有效数字的数量,但不知道如何进行不同类型的舍入.可以用 round 函数来完成,还是在 R 中有不同的函数可以做到这一点?
So I only know how to increase the amount of significant numbers, but not how to do different kinds of rounding. Can that be done with the round function, or is there a different function to do that in R?
推荐答案
使用plyr
包中的round_any
函数:
library(plyr)
x <- 4.34
round_any(x, 3)
[1] 3
round_any(x, 1)
[1] 4
round_any(x, 0.5)
[1] 4.5
round_any(x, 0.2)
[1] 4.4
这篇关于如何在 R 中舍入为 1、1.5、2 等而不是 1、2 或 1.1、1.2、1.3?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文