see the parenthesis of R expressions

No replies
mspiegel's picture
Offline
Joined: 07/31/2009

The following function will let you see the order of operations applied to R expressions.

addParens <- function(expression) {
   input <- match.call()$expression
   return(addParensHelper(input))
}
 
addParensHelper <- function(expression) {
   if (length(expression) == 1) {
      return(expression)
   } else if (expression[[1]] == '(') {
      return(expression)
   } else {
      for(i in 2:length(expression)) {
         expression[[i]] <- addParensHelper(expression[[i]])
      }
      return(substitute((x), list(x = expression)))
   }
}
 
> addParens(2 %x% X %*% Y %*%  t(X))
(((2 %x% X) %*% Y) %*% (t(X)))