Simon Harmel
Simon Harmel

Reputation: 1489

paste two strings to achieve a desired combination

I was wondering how to paste() g and h to obtain my desired combination shown below?

g <- c("compare","control")
h <- "Correlation"

paste0(h, g, collapse = "()") # Tried this with no success

desired <- "Correlation (compare,control)"

Upvotes: 2

Views: 79

Answers (3)

akrun
akrun

Reputation: 887961

Using glue

library(stringr)
glue::glue("{h} ({str_c(g, collapse = ',')})")
Correlation (compare,control)

Upvotes: 1

jay.sf
jay.sf

Reputation: 73802

As an alternative to paste, you could try sprintf in a do.call. String h needs to be expanded by conversion specifications %s, though, by hand or paste("Correlation", '(%s, %s)').

g <- c("compare", "control")
h <- "Correlation (%s, %s)"

do.call(sprintf, c(h, as.list(g)))
# [1] "Correlation (compare, control)"

Upvotes: 0

Sotos
Sotos

Reputation: 51612

Try this,

paste0(h, ' (', toString(g), ')')
#[1] "Correlation (compare, control)"

If you don't want the space in the comma then we can do it manually with paste(), i.e.

paste0(h, ' (', paste(g, collapse = ','), ')')
#[1] "Correlation (compare,control)"

Upvotes: 1

Related Questions