R round 函数

R 的 round 方法是 Math 函数之一,用于将特定数字或表达式舍入到最接近的值。让我们通过一个例子来了解如何使用 round。此编程语言中 round 的语法如下所示。

# numeric_Expression to nearest value 
round(numeric_Expression)

# decimal points to specified integer_value 
round(numeric_Expression, integer_value)

Numeric_Expression:它可以是数值或有效的数值表达式。

  • 如果 numeric_Expression 是正数或负数,则返回最接近的上限值。
  • 如果它不是数字 (NaN),则返回 NaN。如果它是正无穷大或负无穷大,函数将返回相同的值。

R round 函数示例

在此程序中,我们将返回不同数据的 round 值并显示输出。

# Use on Positive  Value
round(45.56)
round(525.4999)

# Use on Negative values
round(-140.825)
round(-13.23)

# Expression
round(140.986 + 122.456 - 220.4233 + 12.67)

# on vectors
number <- c(-22.26, 456.94, 2.50, 2.51, -36.49, -813.111 , -525.123)
round(number)
Round Function on integers and vectors 1

示例 2

在此 程序 中,我们将对不同数据的十进制值进行舍入,并显示输出。

> round(45.565, 0)
[1] 46
> 
> # decimal points to 1 
> round(525.419299, 1)
[1] 525.4
> round(525.419299, 2)
[1] 525.42
> 
> # Use on Negative values
> round(-140.825, 2) 
[1] -140.82
> round(-13.239, 2)
[1] -13.24
> 
> # Expression
> round((140.986 + 122.4563256 - 220.4233 + 12.67), 2)
[1] 55.69
> 
> # vectors
> number <- c(-22.26, 456.94, 2.50, 2.591, -36.49, -813.111 , -525.123)
> round(number, 1)
[1]  -22.3  456.9    2.5    2.6  -36.5 -813.1 -525.1

R round 函数示例 3

在此程序中,我们将把 round 函数应用于 List 数据并显示输出。在此示例中,我们使用 R 提供的 airquality 数据集。

#Dataset We are going to use
airquality

# Applying on Airquality Wind Data
round(airquality$Wind)

round(airquality$Wind, 1)

此函数还允许您舍入数据库或表列中的数值。在此示例中,我们将舍入 [Standard Cost] 和 [Sales Amount] 列中的所有记录。为此,我们将使用下面显示的 CSV 文件数据。

提示:请参阅 Read CSV Function 文章以了解导入 CSV 文件涉及的步骤。

代码

getwd()

#Datat We are going to use
product <- read.csv("Product_Data.csv", TRUE, sep = ",")
print(product)

# Applying on Standard Cost, and Sales Amount
round(product$StandardCost)
round(product$StandardCost, 1)

round(product$SalesAmount)
round(product$SalesAmount, 2)