Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rounding numbers in specific columns of data frame to nearest quarter [duplicate]

I have a dataset, like something below:

    sample1 <-
    structure(list(ID = c( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10), 
    L = c(1.31,  1.62,  1.93,  2.24,  2.55,  2.86,  3.17,  3.48,  3.79,  4.10)), 
    class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA, -10L))

I need to round the "L" column variables to the nearest 0.00, 0.25, 0.5, and 0.75. I really appreciate any help you can provide.

like image 417
Mohammad Haddadi Avatar asked Sep 02 '25 16:09

Mohammad Haddadi


1 Answers

Rounding to the nearest quarter can be accomplished by multiplying the original data by 4, rounding the result, and then dividing by 4 (equivalently, you could divide the original by 0.25, round, and then multiply by 0.25):

sample1$L_round <- round(sample1$L * 4) / 4

      ID     L L_round
   <dbl> <dbl>   <dbl>
 1     1  1.31    1.25
 2     2  1.62    1.5 
 3     3  1.93    2   
 4     4  2.24    2.25
 5     5  2.55    2.5 
 6     6  2.86    2.75
 7     7  3.17    3.25
 8     8  3.48    3.5 
 9     9  3.79    3.75
10    10  4.1     4
like image 105
jdobres Avatar answered Sep 05 '25 08:09

jdobres