Here are a few approaches:
R parsing
rmParen <- function(e) { if (length(e) > 1) { if (identical(e[[1]], as.symbol("("))) e <- e[[2]] if (length(e) > 1) for (i in 1:length(e)) e[[i]] <- Recall(e[[i]]) } e } s <- "( (( A ) * J ) - (( J ) * G ) ) / Z " rmParen(parse(text = s)[[1]])
The last line returns:
(A * J - J * G)/Z
This works in all cases I tried, but you can check it out a little more.
If you need a character string as the return value, use deparse , as in deparse(rmParen(parse(text = s)[[1]])) . Note that deparse has an argument of width.cutoff , which is set to 60 by default, but can be set more if the actual expressions exceed this length.
Ryacas
library(Ryacas) s <- "( (( A ) * J ) - (( J ) * G ) ) / Z " Simplify(s)
The last line returns:
expression((A - G) * J/Z)
Note that this is actually a printing method that calls the calculation, so if you want to save it, try yacas(Simplify(s))$text or as.character(yacas(Simplify(s))) .
ADDED: Ryacas solution.
source share