R语言中的取整函数

R语言中的取整函数

用来取整的四个函数:ceiling floor round trunc,注意四者的区别

ceiling

英文解释:ceiling takes a single numeric argument x and returns a numeric vector containing the smallest integers not less than the corresponding elements of x.

Ceiling接受单个数字参数x,并返回一个数字向量,其中包含不小于x对应元素的最小整数,即向上取整。

参数x可以为单个数值、向量、矩阵。

参数x为单个数值:

image-20221020231502622

参数x为向量:

image-20221020231531812

参数x为矩阵:

image-20221020231614338

floor

英文解释:floor takes a single numeric argument x and returns a numeric vector containing the largest integers not greater than the corresponding elements of x.

Floor接受单个数字参数x并返回一个数字向量,其中包含不大于x对应元素的最大整数,即向下取整。

参数x可以为单个数值、向量、矩阵。

参数x为单个数值:

image-20221021075348856

参数x为向量:

image-20221021075835891

参数x为矩阵:

image-20221021075939441

round

英文解释:round rounds the values in its first argument to the specified number of decimal places (default 0).

四舍五入将第一个参数中的值四舍五入到指定的小数点后位数(默认为0),但会受浮点数影响。

round(x, digits = 0)

x为参数,digits为要保留的位数(默认为0)。

参数x为单个数值:

image-20221021080449309

但是因为计算机内部计算时,会受到浮点数的干扰,所以有时候在.5时会出现问题:

image-20221021085534560

参数x为向量:

image-20221021080721021

参数x为矩阵:

image-20221021080842949

trunc

英文解释:trunc takes a single numeric argument x and returns a numeric vector containing the integers formed by truncating the values in x toward 0.

trunc(x, ...)

Trunc接受单个数字参数x并返回一个数字向量,其中包含通过将x中的值截断到0而形成的整数,即去除小数部分。

参数x为单个数值:

image-20221021085038302

对于大于等于0的数,trunc类似于floor函数,即向下取整;

对于负数,trunc类似于ceiling函数,即向上取整。


版权声明:本文为W_chuanqi原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。