Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R rounding numbers [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 529
Philip John Avatar asked Nov 22 '22 20: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 80
Konrad Avatar answered Jun 02 '23 13:06

Konrad