在 R 中的一条语句下组合一个字符值

Combine a character value under one statement in R

我需要将一个对象组合在一把伞下。

这是一个示例对象。

object <- c("Equal = (G1, 20, Slope[0]); Equal = (G1, 20, Slope[1]);", 
            "Equal = (G1, 21, Slope[0]); Equal = (G1, 21, Slope[1]);",
            "Equal = (G1, 22, Slope[0]); Equal = (G1, 22, Slope[1]);")

> object
[1] "Equal = (G1, 20, Slope[0]); Equal = (G1, 20, Slope[1]);" 
    "Equal = (G1, 21, Slope[0]); Equal = (G1, 21, Slope[1]);"
    "Equal = (G1, 22, Slope[0]); Equal = (G1, 22, Slope[1]);"

我想做的事情如下:

"Equal = (G1, 20, Slope[0]), (G1, 20, Slope[1]),
(G1, 21, Slope[0]), (G1, 21, Slope[1]),
(G1, 22, Slope[0]), (G1, 22, Slope[1]);"

基本上,我需要

(1) combine all under one "Equal" statement.
(2) replace`;` with `,` between statements,
(3) keep one `;` at the end of the object. 

有什么想法吗? 谢谢!

我们可以使用一点正则表达式来做到这一点。

gsub("(?!^);\s{0,1}Equal =", ",", paste(object, collapse = ""), perl = T)

[1] "Equal = (G1, 20, Slope[0]), (G1, 20, Slope[1]), (G1, 21, Slope[0]), (G1, 21, Slope[1]), (G1, 22, Slope[0]), (G1, 22, Slope[1]);"
gsub("[; ]+Equal =",',',paste(object, collapse = ''))

[1] "Equal = (G1, 20, Slope[0]), (G1, 20, Slope[1]), (G1, 21, Slope[0]), (G1, 21, Slope[1]), (G1, 22, Slope[0]), (G1, 22, Slope[1]);"

您可以使用 stringr 中的 str_extract_all() 来提取括号内的所有文本。

library(stringr)

str_c("Equal = ", toString(unlist(str_extract_all(object, "\(.+?\)"))), ";")

# [1] "Equal = (G1, 20, Slope[0]), (G1, 20, Slope[1]), (G1, 21, Slope[0]), (G1, 21, Slope[1]), (G1, 22, Slope[0]), (G1, 22, Slope[1]);"