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.
CodePudding user response:
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)