J.Con
J.Con

Reputation: 4309

Printing significant figures regardless of decimal point

The table below (mean ± se) contains true data that will be presented in a publication. As you can see, the data has a very wide range. Using R, I rounded all numbers to 3 significant figures, but I want to include trailing zeros as well as zeros to the left of the decimal point as significant to try to keep the table tidy. So basically I want ALL numbers, on either side of the decimal point, zeros included, to be considered significant, so that only 3 digits are printed regardless of the number. Is this possible? I have tried signif, round,sprintf,options() and formatC, without success. These results were obtained using x$summary = paste(signif(x$Value, digits=3), "\u00b1", signif(x$se, digits=3))

35.2 ± 3.13 > this is good
124 ± 14.8 > this is good
196 ± 6.53 > this is good
1.34 ± 0.0505 > I would like this to become 1.34 ± 0.05
0.0443 ± 0.00386 > I would like this to become 0.04 ± 0.00
123 ± 0.0067 > I would like this to become 123 ± 0.01

Upvotes: 1

Views: 634

Answers (1)

akrun
akrun

Reputation: 887048

We can try with gsubfn. In the pattern we select the numbers including the dots ([0-9.]+), and replace it by first converting to numeric (as.numeric(x)), and then round it.

library(gsubfn)
gsubfn("[0-9.]+", ~round(as.numeric(x), 2), v1)

In addition to the rounding, we remove the extra characters with substr

gsubfn("[0-9.]+", ~substr(round(as.numeric(x), 3), 1, 4), v1)

Or using sprintf to format the roundded numbers and then replace the extra trailing zeros with sub.

sub("\\.0+\\s|0\\s", " ", gsubfn("[0-9.]+", ~sprintf("%.2f", 
        round(as.numeric(x), 2)), v1))
#[1] "35.2 ± 3.13" "124 ± 14.80" "196 ± 6.53"  "1.34 ± 0.05" "0.04 ± 0.00" "123 ± 0.01" 

data

v1 <- c("35.2 ± 3.13", "124 ± 14.8", "196 ± 6.53", "1.34 ± 0.0505", 
                    "0.0443 ± 0.00386", "123 ± 0.0067")

Upvotes: 2

Related Questions