floor()
floor(x) floor() rounds numeric values down to the nearest integer, toward negative infinity. It’s part of R’s base package and essential for numerical computations requiring integer discretization.
Syntax
floor(x)
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
x | numeric | — | A numeric vector to round down |
Technical Details
The floor function follows the mathematical definition: for any real number x, floor(x) is the greatest integer less than or equal to x.
Key behaviors:
- Positive numbers: floor(3.7) returns 3 (moves left on number line)
- Negative numbers: floor(-2.3) returns -3 (moves left on number line, away from zero)
- Integers unchanged: floor(5) returns 5 (already an integer)
Examples
Basic Usage with Vectors
# Positive numbers
floor(3.7)
[1] 3
# Vector input
floor(c(1.1, 2.5, 3.9, 4.0))
[1] 1 2 3 4
Handling Negative Numbers
# Negative numbers round toward negative infinity
floor(-1.5)
[1] -2
# More examples
floor(-0.1)
floor(-3.7)
floor(-10.0)
[1] -1
[1] -4
[1] -10
The key insight: floor(-1.5) returns -2 because -2 is the largest integer less than or equal to -1.5.
Statistical Binning
# Create continuous data
heights <- c(162.3, 175.8, 183.2, 155.9, 168.7, 172.4, 180.1)
# Bin into 10-unit intervals
floor(heights / 10) * 10
[1] 160 170 180 150 160 170 180
# Create discrete age groups from continuous age data
ages <- c(23.5, 34.2, 45.8, 19.9, 67.1, 52.3)
age_groups <- floor(ages / 10) * 10
age_groups
[1] 20 30 40 10 60 50
This pattern is commonly used for creating histogram bins or demographic categories.
Integer Division Pattern
# Integer division: 7 divided by 3
7 %/% 3
[1] 2
# This is equivalent to:
floor(7 / 3)
[1] 2
# Works with vectors too
a <- c(17, 23, 31, 45)
b <- c(5, 4, 6, 7)
# Integer division using floor()
floor(a / b)
[1] 3 5 5 6
This pattern is useful when you need quotient-only division in calculations.
Common Patterns
Ceiling comparison:
# floor vs ceiling
x <- 2.7
c(floor = floor(x), ceiling = ceiling(x), round = round(x))
floor ceiling round
2 3 3
Data preprocessing:
# Normalize to [0, 1] range then discretize
values <- c(0.12, 0.55, 0.89, 0.34, 0.67)
floor(values * 5) # 5-level discretization
[1] 0 2 4 1 3