You are here

see the parenthesis of R expressions

1 post / 0 new
mspiegel's picture
Offline
Joined: 07/31/2009 - 15:24
see the parenthesis of R expressions

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)))