In scientific paper writing, values are typically reported as rounded values with one, two or three digits, often depending on the type of value reported. This means that everytime when e.g. including an inline mean
value in Rmarkdown I have to add round
to the code.
Thus I am wondering: Is there a way to control number of digits of the output of base functions like e.g. mean()
as an additional argument within the mean()
function? Actually this additional argument would also need to conduct rounding.
Obviously there are a number of ways to control the number of digits, e.g. round(), format()
and sprintf()
or specifying the number of digits in the global option. I do not want the latter option as I need different numbers of digits within the document.
So, what I want is something like:
mean(c(0.34333, 0.1728, 0.5789), digits=2)
which yields the same result as:
round(mean(c(0.34333, 0.1728, 0.5789)), 2)
I know, this is kind of silly, as the number of character to be typed is exactly the same in both chunks. For me the key difference would be that I could write , digits=2)
directly after typing the variable and not having to jump to the beginning of the chunk to add round(
and to the end to add , 2)
.
Any ideas?
The best way I know is using forward-pipe operator %>%
from magrittr
package
> library(magrittr)
> mean(c(0.34333, 0.1728, 0.5789))
[1] 0.36501
> mean(c(0.34333, 0.1728, 0.5789)) %>% round(3)
[1] 0.365
I should also mention, that package magrittr
is used by another very popular package dplyr
, which provides additional functionality for data frame operations. So, when I am using piping, I nearly always write library(dplyr)
, while magrittr
stays behind the scene.