粘贴两个字符串以实现所需的组合

paste two strings to achieve a desired combination

我想知道如何 paste() gh 来获得我下面显示的 desired 组合?

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

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

desired <- "Correlation (compare,control)"

试试这个,

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

如果您不想在逗号中使用 space,那么我们可以使用 paste() 手动完成,即

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

作为 paste 的替代方法,您可以在 do.call 中尝试 sprintf。字符串 h 需要通过转换规范 %s 进行扩展,但可以手动或 paste("Correlation", '(%s, %s)').

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

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

使用glue

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