How to convert R formula to text?

or as an alternative to Julius's version (note: your code was not self-contained)

celkem = 1
rok = 1
mesic = 1
model <- lm(celkem ~ rok + mesic)
paste("my model ", deparse(formula(model)))

A short solution from the package formula.tools, as a function as.character.formula:

frm <- celkem ~ rok + mesic
Reduce(paste, deparse(frm))
# [1] "celkem ~ rok + mesic"

library(formula.tools)
as.character(frm)
# [1] "celkem ~ rok + mesic"

Reduce might be useful in case of long formulas:

frm <- formula(paste("y ~ ", paste0("x", 1:12, collapse = " + ")))

deparse(frm)
# [1] "y ~ x1 + x2 + x3 + x4 + x5 + x6 + x7 + x8 + x9 + x10 + x11 + "
# [2] "    x12"                                                      
Reduce(paste, deparse(frm))
# [1] "y ~ x1 + x2 + x3 + x4 + x5 + x6 + x7 + x8 + x9 + x10 + x11 +      x12"

Which is because of width.cutoff = 60L in ?deparse.


Simplest solution covering everything:

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

Try format :

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

Tags:

R

R Formula