如何在R中使用round()将数字四舍五入
可以使用R中的round()将数字四舍五入。
Round是使数值更有意义并在分析中获得更精确结果的最佳方法之一。
R提供了标准函数round(),也可以根据十进制值对数字进行四舍五入。
从R中的round()语法开始
round()函数的语法如下所示:
round(x,digits=0)
其中:
- x->数值或者可用于四舍五入的向量
- digits->此值表示您希望该数字具有的小数点位数
在R中使用round()舍入数字
你们中的某些人可能知道R可以准确计算最多16位数字。
但是,您始终不需要这16位数字进行分析。
因此,使用R中的round()函数,您也可以轻松地将数字与特定的小数点舍入。
四舍五入单个数值
其中我们将使用功能round()舍入单个值。
如以下输出所示,数字值将指示小数点。
round(143.1234, digits = 0)
输出:143
round(143.1234, digits = 1)
输出:143.1
round(143.1234, digits = 2)
输出:143.12
向量中的值取整
现在,让我们四舍五入存储在向量中的值。
#creates a vector with multiple numerical values in it df<-c(143.236,34.765,789.654,224.568,23.567,9.76) #round off the number in a vector with decimal point 2 round(df, digits = 2)
输出= 143.24 34.77 789.65 224.57 23.57 9.76
df<-c(143.236,34.765,789.654,224.568,23.567,9.76) #round off the number in a vector with decimal point 3 round(df, digits = 3)
输出= 143.236 34.765 789.654 224.568 23.567 9.760
df<-c(143.236,34.765,789.654,224.568,23.567,9.76) #round off the number in a vector with decimal point 0 round(df, digits = 0)
输出= 143 35 790 225 24 10
在R中舍入负数
有时数据也可能包含负值。
让我们看看如何舍入向量中的负值。
df<-c(-143.236,-34.765,-789.654,-224.568,-23.567,-9.76) round(df, 2)
输出= -143.24 -34.77 -789.65 -224.57 -23.57 -9.76
df<-c(-143.236,-34.765,-789.654,-224.568,-23.567,-9.76) round(df)
输出= -143 -35 -790 -225 -24 -10
注意:请记住,如果您未提及数字,则默认情况下,它将被视为0,如上所示。
另外,请注意,不管指定的整数值的类型如何,过程如何继续保持相同。
四舍五入表达式中的值
在R中使用round(),我们可以轻松舍入表达式中的数字。
round()函数将求解该表达式,并用2个小数点舍入最终值,如下所示。
#creats an expression my_expression<- c(34.567+234.6789-234.67+567.8) #round off the values in an expression round(my_expression)
输出= 602.38
在R中使用round()对数据集中的值进行舍入
我们已经研究了round()函数的各个方面。
我们将虹膜数据集中的值四舍五入。
df<- datasets::iris df
虹膜数据集视图
round(iris$Sepal.Length,0)
输出=所有值均以0小数点舍入。
[1] 5 5 5 5 5 5 5 5 4 5 5 5 5 4 6 6 5 5 6 5 5 5 5 5 5 5 5 5 5 5 5 5 5 6 5 5 [37] 6 5 4 5 5 4 4 5 5 5 5 5 5 5 7 6 7 6 6 6 6 5 7 5 5 6 6 6 6 7 6 6 6 6 6 6 [73] 6 6 6 7 7 7 6 6 6 6 6 6 5 6 7 6 6 6 6 6 6 5 6 6 6 6 5 6 6 6 7 6 6 8 5 7 [109] 7 7 6 6 7 6 6 6 6 8 8 6 7 6 8 6 7 7 6 6 6 7 7 8 6 6 6 8 6 6 6 7 7 7 6 7 [145] 7 7 6 6 6 6
Signif()函数将数字取整
如果您想知道,signif()是什么?它就像一个舍入函数,但是它只寻找总数而不是小数点。
signif(34.567, 3)
输出= 34.6
其中您可以观察到signif()函数将舍入位数的总数。
它不处理小数点。
signif(34.567, 5)