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为单个数值:
参数x为向量:
参数x为矩阵:
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为单个数值:
参数x为向量:
参数x为矩阵:
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为单个数值:
但是因为计算机内部计算时,会受到浮点数的干扰,所以有时候在.5
时会出现问题:
参数x为向量:
参数x为矩阵:
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为单个数值:
对于大于等于0的数,trunc类似于floor函数,即向下取整;
对于负数,trunc类似于ceiling函数,即向上取整。