I will need to combine an object under one umbrella.
Here is a sample object.
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]);"
what I would like to do is as below:
"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]);"
Basically, I need to
(1) combine all under one "Equal" statement.
(2) replace`;` with `,` between statements,
(3) keep one `;` at the end of the object.
Any ideas? Thanks!
CodePudding user response:
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]);"
CodePudding user response:
We can use a little regex to do so.
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]);"
CodePudding user response:
You can use str_extract_all()
from stringr
to extract all texts surrounded by parentheses.
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]);"