How to round a data.frame in R that contains some character variables?

I think the neatest way of doing this now is using dplyr

library(dplyr)
df %>% 
 mutate_if(is.numeric, round)

This will round all numeric columns in your dataframe


Recognizing that this is an old question and one answer is accepted, I would like to offer another solution since the question appears as a top-ranked result on Google.

A more general solution is to create a separate function that searches for all numerical variables and rounds them to the specified number of digits:

round_df <- function(df, digits) {
  nums <- vapply(df, is.numeric, FUN.VALUE = logical(1))

  df[,nums] <- round(df[,nums], digits = digits)

  (df)
}

Once defined, you can use it as follows:

> round_df(df, digits=3)

Tags:

R