How to Use ceiling() Function in R (5 Examples)

The ceiling() function in R “is used to return the smallest integer value, greater than or equal to a specific number, or an expression”. For example, ceiling(3.14) returns 4.

Syntax

 ceiling(x)

Parameters

The ceiling() function accepts one parameter whose value needs to be rounded off.

  1. If the x parameter is a positive or negative numeric value, the ceiling function returns the ceiling value.
  2. If it is a positive or negative Zero value, the ceiling(,) function returns Zero.
  3. If the x is Not a Number (NaN), the ceiling returns NaN.
  4. If the x is positive or negative infinity, the function returns the same as the input.

Return value

The ceiling() function returns the smallest integer greater than or equal to the number sent as a parameter.

Example 1: How to use the ceiling() function in R

dice <- ceiling(1.9)
ace <- ceiling(2.1)
club <- ceiling(4.5)

print(dice)
print(ace)
print(club)

Output

[1] 2
[1] 3
[1] 5

The output shows that the ceiling() function rounds up 1.9 to 22.1 to 3, and 4.5 to 5.

Example 2: Passing negative values to ceiling() function

Let’s pass the negative arguments to R’s ceiling() function.

dice <- ceiling(-1.9)
ace <- ceiling(-2.1)
club <- ceiling(-4.5)

print(dice)
print(ace)
print(club)

Output

[1] -1
[1] -2
[1] -4

Example 3: Ceiling value of an expression

Let’s pass the numeric expression to the ceil() function and see the output.

joker <- ceiling(0.8 + 12.45 - 20.3 + 333)
print(joker)

Output

[1] 326

Example 4: Use the ceiling() function with R Vectors

To find the ceil values of vectors in R, use the ceiling() function. The ceiling() function returns the ceiling value of each vector element.

hearts <- c(-21.19, 46.21, -11.10, -9.11, -0.123)
ceiling(hearts)

Output

[1] -21 47 -11 -9 0

Example 5: Use the ceiling() function with List

To find the ceiling value of each element of the R List, access elements one by one and pass that element to the ceiling() function, which will return the R List’s ceiling value.

diamond <- list(10.21, 11.21, 19.21, 29.10)
ceiling(diamond[[1]])
ceiling(diamond[[2]])
ceiling(diamond[[3]])
ceiling(diamond[[4]])

Output

[1] 11
[1] 12
[1] 20
[1] 30

That’s it.

Leave a Comment