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.
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.
To round values in proportion table in R, we can first save the proportion table in an object and then use the round function.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With