Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rounding values in a dataframe in R [duplicate]

Tags:

r

I have a dataframe values as shown below

January  February  March
0.02345  0.03456   0.04567
0.05432  0.06543   0.07654

I need a command to round each of these values to 3 decimal points. Output should be as shown below

January  February  March
0.023    0.035     0.046
0.054    0.065     0.077
like image 798
Philip John Avatar asked Nov 28 '22 01:11

Philip John


1 Answers

In case your data frame contains non-numeric characters you may be willing to make use of the function by Jeromy Anglim:

round_df <- function(x, digits) {
    # round all numeric variables
    # x: data frame 
    # digits: number of digits to round
    numeric_columns <- sapply(x, mode) == 'numeric'
    x[numeric_columns] <-  round(x[numeric_columns], digits)
    x
}

round_df(data, 3)

I think it's neat and quick approach to handle the rounding problem across heterogeneous data frames.

like image 69
Konrad Avatar answered Jun 02 '23 14:06

Konrad