Search code examples
rdataframerounding

Rounding numbers in specific columns of data frame to nearest quarter


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.


Solution

  • 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