rr-formula

How to convert R formula to text?


I have trouble working with formula as with text. What I'm trying to do is to concatenate the formula to the title of the graph. However, when I try to work with the formula as with text, I fail:

model <- lm(celkem ~ rok + mesic)
formula(model)
# celkem ~ rok + mesic

This is fine. Now I want to build string like "my text celkem ~ rok + mesic" - this is where the problem comes:

paste("my text", formula(model))
# [1] "my text ~"           "my text celkem"      "my text rok + mesic"

paste("my text", as.character(formula(model)))
# [1] "my text ~"           "my text celkem"      "my text rok + mesic"

paste("my text", toString(formula(model)))
# [1] "my text ~, celkem, rok + mesic"

Now I see there is a sprint function in package gtools, but I think this is such a basic thing that it deserves a solution within the default environment!!


Solution

  • Simplest solution covering everything:

    f <- formula(model)
    paste(deparse(f, width.cutoff = 500), collapse="")