Reputation: 35
a="1-B*(0.5+c1)+B**2*(-c2+0.5*c1)+0.5*c3*B**3"
I want to breakdown the above character string as
B, -(0.5+c1), B**2, (-c2+0.5c1), B**3, 0.5*c3
using R. Any suggestions?
Upvotes: 0
Views: 280
Reputation: 10233
While not exactly what you want as output, the following is sufficiently close and might help you solve the problem:
a <- "1-B*(0.5+c1)+B**2*(-c2+0.5*c1)+0.5*c3*B**3"
b <- gsub("**", "^", a, fixed = TRUE) # Replace "**" with "^" to simply the regex
ans <- unlist(strsplit(b, '\\([^)]*\\)(*SKIP)(*F)|\\*|\\+', perl = TRUE))
print(ans)
#[1] "1-B" "(0.5+c1)" "B^2" "(-c2+0.5*c1)" "0.5" "c3"
#[7] "B^3"
More on the regular expression used can be found here.
You can easily change the "^"
back to "**"
using gsub
.
I see no easy way to attach the negative sign of B
to the coefficient.
Upvotes: 1