Search code examples
rconcatenationstring-concatenation

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.


Solution

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