Skip to content
Prev 397651 / 398500 Next

Creating model formulas programmatically

On 2025-03-30 11:41 a.m., Bert Gunter wrote:
You can avoid the parens with

recurseCall2 <- function(nms, FUN = '+')
{  n <- length(nms)
    if(n > 2) call(FUN, Recall(nms[-n]), nms[[n]])
    else call(FUN, nms[[1]],nms[[2]])
}

By the way, your original recurseCall produces a slightly unusual 
object.  For some weird historical reasons, parens in R expressions are 
parsed as function calls, they don't just affect order of operations. 
So if you do

  e <- quote(Heigh + (Ho + (Silver + Away)))
  as.list(e[[3]])

you'll see this display:

[[1]]
`(`

[[2]]
Ho + (Silver + Away)

However, with the output of your function you'll see

  e <- recurseCall(nms)
  as.list(e[[3]])

[[1]]
`+`

[[2]]
Ho

[[3]]
Silver + Away

because in your object the parens were added during deparsing, they 
aren't stored as part of the object.

Duncan Murdoch