Controlling numbers / rounding as an argument in base functions

When writing a scientific article, values ​​are usually reported as rounded values ​​with one, two or three digits, often depending on the type of value reported. This means that every time, for example, including an embedded value mean

in Rmarkdown. I need to add round

to the code.

So my question is: is there a way to control the number of digits in the output of basic functions, for example, mean()

as an additional argument in a function mean()

? In fact, this additional argument would also have to do rounding.

Obviously there are several ways to control the number of digits, for example. round(), format()

and sprintf()

or specify the number of digits in the global option. I don't need the latter option as I need a different number of digits in the document.

So, I want something like: mean(c(0.34333, 0.1728, 0.5789), digits=2)

which gives the same result as: round(mean(c(0.34333, 0.1728, 0.5789)), 2)

I know this is stupid, since the number of characters to be typed is exactly the same in both pieces. For me, the key difference would be that I could write , digits=2)

directly after entering the variable and not go to the beginning of the snippet to add round(

and until the end of add , 2)

.

Any ideas?

+3


source to share


1 answer


The best way I know is to use the 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

      



It should also be mentioned that the package is magrittr

used by another very popular package dplyr

that provides additional functionality for manipulating data frames. So when I use piping, I almost always write library(dplyr)

and magrittr

stay behind the scenes.

+2


source







All Articles