R removes redundant parentheses from a formula or expression string

I have many formula lines similar to this:

str <- "( (( A ) * J ) - (( J ) * G ) ) / Z " 

There are many parentheses that do not have to be there, (A*J - J*G)/Z Is there a function or package in R that can take care of this?

I tried functions for R expressions as well as as.formula , but did not find what I needed.

+6
source share
2 answers

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.

+4
source

We can use the R-parser to complete the task. The trick is that R knows when parentheses are needed based on the parsing tree, so we can just remove them from the tree:

See this:

 simplify <- function(e) { if( mode(e) %in% c("name","numeric") ) return(e) op <- as.character(e[[1]]) if( op == "(" ) return(simplify(e[[2]])) if( op %in% c("+","-","*","/","^") ) return(call(op, simplify(e[[2]]), simplify(e[[3]]))) } simplifytext <- function(s) deparse(simplify(parse(text=s)[[1]])) 

Inputs

 str <- "( (( A ) * J ) - (( J ) * G ) ) / Z " str2 <- gsub("-", "/", gsub("*", "+", str, fixed=TRUE)) 

Results:

 > str2 [1] "( (( A ) + J ) / (( J ) + G ) ) / Z " > simplifytext(str) [1] "(A * J - J * G)/Z" > simplifytext(str2) [1] "(A + J)/(J + G)/Z" 
+5
source

Source: https://habr.com/ru/post/947852/


All Articles