Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Convert a R column of decimal to the 6th decimal place

Say that I have a R data frame df:

   id   value
0  a    0.00016
1  b    0.0324789
2  c    0.05583726
3  d    0.02

How can I convert `df$value$ into decimals with exactly 6 decimal places like the following?

   id   value
0  a    0.000160
1  b    0.032478
2  c    0.005837
3  d    0.020000

I tried to use round(df$value, digits=6) but it only truncates the ones with the more than 6 decimal places but fails to add more zeros to the ones with less than 6 decimal places.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Instead of using round() I use format()

x <- tribble(~id,   ~value,
 "a",    0.00016,
  "b",    0.0324789,
  "c",    0.05583726,
  "d",    0.02)

x %>% mutate(value_digits=format(value,nsmall = 6))

I get the below output:

  id      value value_digits
  <chr>   <dbl> <chr>       
1 a     0.00016 0.000160    
2 b     0.0325  0.032479    
3 c     0.0558  0.055837    
4 d     0.02    0.020000    

BASE R

#assume x to be the name of the dataframe
x$value <- format(x$value,nsmall=6)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading