Is it possible to make print.formula respect the environment width option?
The formula print method does not respect the environment width option.
For example, given the following long formula:
fo <- y ~ factor1 + factor2 + factor3 + factor4 + factor5 + factor6 + factor7 + factor8
Set the environment width fairly narrow
options(width=30)
And print the formula
print(fo)
Results开发者_开发技巧 in (regardless of the width option)
y ~ factor1 + factor2 + factor3 + factor4 + factor5 + factor6 +
factor7 + factor8
Any ideas how to make print.formula respect the width option?
You can use a combination of strwrap
and capture.output
:
fo <- y ~ factor1 + factor2 + factor3 + factor4 + factor5 + factor6 + factor7 + factor8
options(width=30)
strwrap(capture.output(print(fo)))
[1] "y ~ factor1 + factor2 +"
[2] "factor3 + factor4 +"
[3] "factor5 + factor6 +"
[4] "factor7 + factor8"
You could hack around with print.formula
, but the easiet thing to do is to wrap the output in strwrap
, which does respect getOption("width")
.
cat(strwrap(fo), sep = "\n")
Conversion to character transposes the first two elements, so you need to do a little fixing up first.
ch_fo <- paste(as.character(fo)[c(2,1,3)], collapse = " ")
cat(strwrap(ch_fo), sep = "\n")
Using deparse
is another option.
deparse(fo, width.cutoff = getOption('width'))
I ended up going with a sightly different approach:
print.f <- function(f) {
cat(paste(deparse(f, width.cutoff=getOption("width")), collapse="\n"))
}
It respects the environment's width setting, while printing the naked (not a string vector) formula with correct indenting.
精彩评论