Reputation: 10291
Using knitr, I want to print the results of several functions for some variable, e.g.
There were x1 (a=\`r a(x1)\`; b=\`r b(x1)\`) and x2 (a=\`r a(x2)\`; b=\`r b(x2)\`)
Since I don't like to repeat this for every variable, I wrote a function to generate the string:
foo <- function(x) paste('a = ',a(x), '; b = ', b(x))
Now I can write There were x1 (`r foo(x1)`) and x2 (`r foo(x2)`)
.
It works, but doesn't use options('digits')
, so it prints 15 digits. cat()
uses options('digits')
, but apprently using cat is discouraged and doesn't output anything when using inline code.
Is there an alternative to paste()
that formats numbers with `options('digits') and creates output in inline chunks?
Upvotes: 3
Views: 1464
Reputation: 10215
"Using of cat discouraged": this is a misunderstanding. Yihui warns against using cat
to output messages. If you want to created clean output, you often must use cat. Try the following in your chunk:
options(digits=2)
x1 = 2.304302
# chunk output
x1 # Ugly, [1]
cat(x1,"\n") # Must use cat here, to avoid the [1] printed
Re you main question: No chance here without explicit formating in your foo
function, probably best with sprintf
. Options
only applies in the inline numeric code, not to strings as supplied by your function foo
. knitr
does not interfere with the function of paste
, and paste does not honor options
.
x2 = 4.489324802
options(digits=2)
paste(x2)
"4.489324802"
Upvotes: 3