简体   繁体   中英

How can I get this exact formatting in R?

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 (eg 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"

I am not proud of this solution, but gsub +regex does the job now fine.

> df$c <- gsub('\\.$', '',formatC(signif(df$a,digits=3), digits=3,format="fg", flag="#"))
> 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM