Skip to main content
 首页 » 编程设计

R语言数据四舍五入函数教程

2022年07月19日152myhome

在实践中,数字并不总是像它们在理论上那样好理解,因为实际产生的数据往往小数较多。因此通常有必要对数字进行四舍五入,以使它们更具可读性。 本文介绍 R 提供的几个类似功能函数,进行对比学习。

数据四舍五入

两个数据相除结果可能包括很多小数,一般需要进行四舍五入。四舍五入可以有多种方式实现,大多数语言都类似函数,R也一样。你可以向上或向下四舍五入,也可以四舍五入到最接近的整数或预定的数字。因此需要几个不同函数实现。

round 函数

语法如下,number是需要四舍五入的数字,digits是保留小数位数。请示例:

#  round(number,digits) 
 
round(1234.56789,3) 
# [1] 1234.568 
round(1234.56789,0) 
# [1] 1235 
round(1234.56789,-3) 
# [1] 1000 

digit为正数会影响小数点后面数,负数则影响小数点前面的数。

signif 函数

语法如下,digits表示整个数据保留的位数:

# signif(number,digits) 
signif(1234.566789,4) 
# [1] 1235 
signif(1234.566789,7) 
# [1] 1234.567 
signif(1234.566789,1) 
# [1] 1000 

signif函数取整到给定的数字位数。round和signif函数都使用标准的舍入约定。

floor 函数

floor四舍五入至到小于它的最近整数:

# floor in r example  
floor(3.14159) 
# [1] 3 
floor(-3.14159) 
# [1] -4 

我们看到floor函数总是向下取最近的整数。

ceiling 函数

ceiling函数四舍五入至大于它的最近整数:

# ceiling in R example  
ceiling(3.14159) 
# [1] 4 
ceiling(-3.14159) 
# [1] -3 

ceiling函数总是向上取最近整数。

trunc 函数

Tranc函数仅保留整数部分,直接舍去小数。

#Trunc in R example  
trunc(3.14159) 
# [1] 3 
trunc(-3.14159) 
# [1] -3 

其他方案

四舍五入函数应用较多,因为大多数函数不能产生简洁好懂的结果。R的舍入函数不仅处理单个数字,它们还可以舍入整个向量数据。甚至可以处理整个R数据框。舍入一个完整的R数据帧的主要限制是舍入函数只能处理数值。这个问题的解决方案是首先处理数值列,将它们四舍五入,然后再使用cbind函数进行绑定。

还可以使用print函数:

# options(digits = 2) 
mydf <- data.frame(January = c(0.02345, 0.05432), February = c(0.03456, 0.06543),  
                   March = c(0.04567, 0.07654), non_numeric = c("abcdefgh", "ijklmno")) 
mydf 
#   January February   March non_numeric 
# 1 0.02345  0.03456 0.04567    abcdefgh 
# 2 0.05432  0.06543 0.07654     ijklmno 
 
print(mydf, digits = 2) 
#   January February March non_numeric 
# 1   0.023    0.035 0.046    abcdefgh 
# 2   0.054    0.065 0.077     ijklmno 

对于数据框中包含字符串列,我们可以自己定义函数实现:

round_df <- function(x, digits) { 
    # round all numeric variables 
    # x: data frame  
    # digits: number of digits to round 
    numeric_columns <- sapply(x, mode) == 'numeric' 
    x[numeric_columns] <-  round(x[numeric_columns], digits) 
    x 
} 
 
round_df(data, 3) 

本文参考链接:https://blog.csdn.net/neweastsun/article/details/120973183
阅读延展