I tried playing around with signif
or formatC
, but didn't get the result, no matter which of the options I used. I could write my own function... but I am sure there is a solution.
The following code provides an example data frame. Column a
presents the numerical input column and column b
the expected "rendered" character output.
The numbers have to be rounded to three significant digits (e.g. signif
)
> data.frame(a=c(1,23,456,1.23,23.46,456.78,1234),b=c("1.00","23.0","456","1.23","23.5","457","1230"))
a b
1 1.00 1.00
2 23.00 23.0
3 456.00 456
4 1.23 1.23
5 23.46 23.5
6 456.78 457
7 1234.00 1230
Edit: This is the output for the proposed solution:
> df <- data.frame(a=c(1,23,456,1.23,23.46,456.78,1234),b=c("1.00","23.0","456","1.23","23.5","457","1230"))
> df$c <- print(formatC(signif(df$a,digits=3), digits=3,format="fg", flag="#"))
[1] "1.00" "23.0" "456." "1.23" "23.5" "457." "1230."
> df
a b c
1 1.00 1.00 1.00
2 23.00 23.0 23.0
3 456.00 456 456.
4 1.23 1.23 1.23
5 23.46 23.5 23.5
6 456.78 457 457.
7 1234.00 1230 1230.
Can we now remove the decimal point for the numbers 456, 457 and 1230?
Check the Signif
function from VFP
package.
VFP:::Signif(df$a, 3)
[1] "1.00" "23.0" "456" "1.23" "23.5" "457" "1230"