Round Only Numeric Variables of Data Frame in R (Example Code)
In this tutorial, I’ll illustrate how to round numeric variables of a mixed data frame in R.
Example Data
data(iris) # Loading iris data head(iris) # Display head of iris data set # Sepal.Length Sepal.Width Petal.Length Petal.Width Species # 1 5.1 3.5 1.4 0.2 setosa # 2 4.9 3.0 1.4 0.2 setosa # 3 4.7 3.2 1.3 0.2 setosa # 4 4.6 3.1 1.5 0.2 setosa # 5 5.0 3.6 1.4 0.2 setosa # 6 5.4 3.9 1.7 0.4 setosa |
data(iris) # Loading iris data head(iris) # Display head of iris data set # Sepal.Length Sepal.Width Petal.Length Petal.Width Species # 1 5.1 3.5 1.4 0.2 setosa # 2 4.9 3.0 1.4 0.2 setosa # 3 4.7 3.2 1.3 0.2 setosa # 4 4.6 3.1 1.5 0.2 setosa # 5 5.0 3.6 1.4 0.2 setosa # 6 5.4 3.9 1.7 0.4 setosa
Example: Round Only Numeric Columns of Data Frame with Factors & Characters
install.packages("dplyr") # Install dplyr package library("dplyr") # Load dplyr package |
install.packages("dplyr") # Install dplyr package library("dplyr") # Load dplyr package
iris_round <- iris %>% # Applying mutate_if function mutate_if(is.numeric, round, digits = 0) head(iris_round) # Display head of rounded data frame # Sepal.Length Sepal.Width Petal.Length Petal.Width Species # 1 5 4 1 0 setosa # 2 5 3 1 0 setosa # 3 5 3 1 0 setosa # 4 5 3 2 0 setosa # 5 5 4 1 0 setosa # 6 5 4 2 0 setosa |
iris_round <- iris %>% # Applying mutate_if function mutate_if(is.numeric, round, digits = 0) head(iris_round) # Display head of rounded data frame # Sepal.Length Sepal.Width Petal.Length Petal.Width Species # 1 5 4 1 0 setosa # 2 5 3 1 0 setosa # 3 5 3 1 0 setosa # 4 5 3 2 0 setosa # 5 5 4 1 0 setosa # 6 5 4 2 0 setosa
Related Articles
You may find some related R tutorials on topics such as numeric values, variables, and data conversion below.