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

I have a dataframe, and I wish to round all of the numbers (ready for export). This must be straightforward, but I am having problems because some bits of the dataframe are not numeric numbers. For example I want to round the figures to the nearest whole number in the example below:

ID = c("a","b","c","d","e")
Value1 = c("3.4","6.4","8.7","1.1","0.1")
Value2 = c("8.2","1.7","6.4","1.9","10.3")
df<-data.frame(ID,Value1,Value2)

Can anyone help me out? I can round individual columns (e.g., round(df$Value1, 2)) but I want to round a whole table which contains some columns which are not numeric.


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)

First make sure your number columns are numeric:

ID = c("a","b","c","d","e")
Value1 = as.numeric(c("3.4","6.4","8.7","1.1","0.1"))
Value2 = as.numeric(c("8.2","1.7","6.4","1.9","10.3"))
df<-data.frame(ID,Value1,Value2, stringsAsFactors = FALSE)

Then, round only the numeric columns:

df[,-1] <-round(df[,-1],0) #the "-1" excludes column 1
df

  ID Value1 Value2
1  a      3      8
2  b      6      2
3  c      9      6
4  d      1      2
5  e      0     10

I know this is a late reply, but I also had this same problem. After doing some searching I found this to be the most elegant solution:

data.frame(lapply(x, function(y) if(is.numeric(y)) round(y, 2) else y)) 

Solution originally from: Jean V. Adams Statistician U.S. Geological Survey Great Lakes Science Center 223 East Steinfest Road Antigo, WI 54409 USA

http://r.789695.n4.nabble.com/round-a-data-frame-containing-character-variables-td3732415.html


Here is a one-liner that I like using: (this will apply the round function to only the columns of class type specified in the classes argument)

df2 <- rapply(object = df, f = round, classes = "numeric", how = "replace", digits = 0)