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.

2 Answers 2

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)
Sign up to request clarification or add additional context in comments.

1 Comment

@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
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)"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.