0

Here's a dataset - it's got an estimate of a quantity, along with two cells for the lower and upper bounds of a 95% confidence interval for that estimate:

d <- data.frame(estimate = c(380.3),
                low_95 = c(281.6),
                high_95 = c(405.7))

I'd like to concatenate each of these cells into one new string -- only I'd like to add some character elements so that the result is a single cell that looks like this:

380.3 (281.6, 405.7)

I've fiddled with unite in dplyr based on this post, but I can't even get the numbers to stick together with an underscore, much less insert spaces, parentheses, and a comma.

logjammin
  • 1,121
  • 6
  • 21

2 Answers2

4

We can use sprintf in base R

with(d, sprintf('%.1f (%.1f, %.1f)', estimate, low_95, high_95))
#[1] "380.3 (281.6, 405.7)"

Or without specifying the arguments one by one, use do.call

do.call(sprintf, c(fmt = '%.1f (%.1f, %.1f)', d))
#[1] "380.3 (281.6, 405.7)"

Or another option is glue

library(dplyr)
library(glue)
d %>% 
  glue_data("{estimate} ({low_95}, {high_95})")
#380.3 (281.6, 405.7)
akrun
  • 874,273
  • 37
  • 540
  • 662
  • 2
    @logjammin The example you showed is having only numeric columns. If your original data is `character` class, then change it to `%s`. Please check `str(d)` to check the class of each column – akrun May 30 '21 at 05:20
1

Well you can use the paste0 command that is part of the base R package, to concatenate strings in R. For example:

result <- paste0(d$estimate, " (", d$low_95, ", ", d$high_95, ")")
print(result)

[1] "380.3 (281.6, 405.7)"
Nadir Latif
  • 3,690
  • 1
  • 15
  • 24