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

paste two strings to achieve a desired combination

提问人:Simon Harmel 提问时间:12/24/2021 最后编辑:Simon Harmel 更新时间:12/25/2021 访问量:69

问:

我想知道如何获得如下所示的组合?paste()ghdesired

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

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

desired <- "Correlation (compare,control)"
r 字符串 字符 粘贴

评论


答:

1赞 Sotos 12/24/2021 #1

试试这个,

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

如果您不想要逗号中的空格,那么我们可以手动使用 ,即paste()

paste0(h, ' (', paste(g, collapse = ','), ')')
#[1] "Correlation (compare,control)"
0赞 jay.sf 12/24/2021 #2

作为 的替代方法,您可以尝试使用 .字符串需要通过转换规范进行扩展,但是,手动或.pastesprintfdo.callh%spaste("Correlation", '(%s, %s)')

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

do.call(sprintf, c(h, as.list(g)))
# [1] "Correlation (compare, control)"
1赞 akrun 12/25/2021 #3

glue

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