Home > Back-end >  paste two strings to achieve a desired combination
paste two strings to achieve a desired combination

Time:12-24

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

CodePudding user response:

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

CodePudding user response:

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