logjammin
logjammin

Reputation: 1211

In R, concatenate numeric columns into a string while inserting some text elements

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.

Upvotes: 0

Views: 811

Answers (2)

Nadir Latif
Nadir Latif

Reputation: 3773

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

Upvotes: 1

akrun
akrun

Reputation: 887771

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)

Upvotes: 4

Related Questions