Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

r

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.

like image 492
KT_1 Avatar asked Jan 30 '12 12:01

KT_1


People also ask

How do you round a variable in a DataFrame in R?

Round function in R, rounds off the values in its first argument to the specified number of decimal places. Round() function in R rounds off the list of values in vector and also rounds off the column of a dataframe. It can also accomplished using signif() function.

How do I round all values in a table in R?

To round values in proportion table in R, we can first save the proportion table in an object and then use the round function.


2 Answers

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

like image 185
user1165199 Avatar answered Sep 26 '22 13:09

user1165199


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) 
like image 35
akhmed Avatar answered Sep 24 '22 13:09

akhmed