 # The floor() function in R This tutorial will show you how to use the floor() function in R to round down a float number to the nearest integer. Let’s read it now to get more knowledge.

## What is the floor() function in R?

The floor() function takes a float number as the input and then rounds it down to the nearest integer.

Syntax:

floor(input)

Parameter:

• input: A float number, a float vector, a data frame’s column.

## How to use the floor() function?

Now, we will discover how to use the floor() function to round down some popular data types in R.

### Use the floor() function to round a float number down

The simplest example is using the floor() function to round a float number down. Look at the following example.

Code:

# Declare a float number
myFloat = 22.6

# Round the number down
myInt = floor(myFloat)

cat("The original number is", myFloat)
cat("\nThe number after using the floor() function is", myInt)

Result:

The original number is 22.6
The number after using the floor() function is 22


### Use the floor() function to round a float vector down

In this part, we will use the floor() function to round a float vector down to an integer vector.

Code:

# Declare a float vector
floatVect = c(1.3, 23.4, 12.4, 6.6, 72.4, 54.9)

# Round the vector down
intVect = floor(floatVect)

cat("The original number is:\n", floatVect)
cat("\nThe number after using the floor() function is:\n", intVect)

Result:

The original number is:
1.3 23.4 12.4 6.6 72.4 54.9
The number after using the floor() function is:
1 23 12 6 72 54


### Use the floor() function to round a float data frame’s column

Sometimes, you will need to round down values in a data frame, such as in the example below.

Code:

# Create vector dispaying house's information
Square = c(54.3, 34.5, 30.5, 43.6, 51.2, 43.2, 37.0)
Room = c(4, 3, 3, 3, 5, 3, 3)
Floor = c(3, 3, 3, 2, 3, 2, 2)
Price = c(210200, 180300, 156000, 192320, 212300, 187600, 170000)

# Create a data frame
house = data.frame(Square, Room, Floor, Price)

# Round the Square column down
house$Square = floor(house$Square)

cat("The data frame after using the floor() function:\n")
print(house)

Result:

The data frame after using the floor() function:
Square Room Floor   Price
1     54    4     3  210200
2     34    3     3  180300
3     30    3     3  156000
4     43    3     2  192320
5     51    5     3  212300
6     43    3     2  187600
7     37    3     2  170000


## Summary

In summary, the floor() function rounds a float number down to the nearest integer. However, you can use the function to apply to other data types, such as vectors or data frames, to get the expected results.

Maybe you are interested:

Posted in R