R ceiling() 与 floor() 函数 - 向上向下取整
R 提供了多种取整函数:ceiling() 向上取整、floor() 向下取整、trunc() 向零截断。
这些函数在数值离散化、分箱处理和资源分配计算中经常使用。
各函数语法格式如下:
ceiling(x) # 向上取整(不小于 x 的最小整数) floor(x) # 向下取整(不大于 x 的最大整数) trunc(x) # 向零方向截断
参数说明:
x 输入数值或数值向量。
实例
x <- c(3.14, -3.14, 5.99, -5.99, 2.0)
# ceiling: 向上取整
print("ceiling(向上):")
print(ceiling(x))
# floor: 向下取整
print("floor(向下):")
print(floor(x))
# trunc: 向零截断
print("trunc(向零截断):")
print(trunc(x))
# ceiling: 向上取整
print("ceiling(向上):")
print(ceiling(x))
# floor: 向下取整
print("floor(向下):")
print(floor(x))
# trunc: 向零截断
print("trunc(向零截断):")
print(trunc(x))
执行以上代码输出结果为:
[1] "ceiling(向上):" [1] 4 -3 6 -5 2 [1] "floor(向下):" [1] 3 -4 5 -6 2 [1] "trunc(向零截断):" [1] 3 -3 5 -5 2
ceiling() 在分页计算中非常实用:
实例
# 分页计算:每页显示 20 条数据
total_items <- 103
items_per_page <- 20
# 计算需要的总页数(向上取整)
total_pages <- ceiling(total_items / items_per_page)
print(paste(total_items, "条数据,每页", items_per_page,
"条,共需", total_pages, "页"))
total_items <- 103
items_per_page <- 20
# 计算需要的总页数(向上取整)
total_pages <- ceiling(total_items / items_per_page)
print(paste(total_items, "条数据,每页", items_per_page,
"条,共需", total_pages, "页"))
执行以上代码输出结果为:
[1] "103 条数据,每页 20 条,共需 6 页"

R 语言实例