简体   繁体   中英

Converting numbers to string in R while retaining trailing zeros/negative signs

I have a dataset with the estimate and lower/upper bounds of the 95% confidence interval.

Here is example code:

data <- as.data.frame(cbind(-0.6142, -1.2190, -0.0092))

colnames(data) <- cbind("Estimate", "LowerCI", "UpperCI")

paste(as.character(round(data$Estimate,1)), '(', as.character(round(data$LowerCI,1)), ',', as.character(round(data$UpperCI,1)), ')')

I am trying to create a variable that I can output to Word that will look like this: -0.6 (-1.2, -0.0)

But I end up with: -0.6 ( -1.2, 0 )

The problems are:

  1. The spacing is off; there is a space before/after -1.2, and a space before/after 0.0
  2. There is no trailing zero
  3. Ideally I would like to have the negative sign in front of the 0 ("-0.0") to convey that the 95% confidence interval does not cross zero.

I'd appreciate any tips.

You can use sprintf with the format string "%01.1f" for this:

x = c(-0.6142, -1.2190, -0.0092)
sprintf(fmt = "%01.1f", x)
[1] "-0.6" "-1.2" "-0.0"

You can also use sprintf to put it all together:

with(data, sprintf(fmt = "%01.1f (%01.1f, %01.1f)", Estimate, LowerCI, UpperCI))
# [1] "-0.6 (-1.2, -0.0)"

I don't have it it in me to really explain - I'd recommend skimming the ?sprintf help page, running the examples at the bottom of the page, and then reading the page more carefully if you'd like to understand the nuances.

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