On Nov 10, 2010, at 9:51 AM, Liliana Pacheco wrote:
> Hi R users
> I have a very simple function. As the return of that function I want the
> answer with 5 decimal places, but it hasn't worked with sprintf, nor
with
> format, nor print. This is how I used sprintf:
>
> cuant<-function(r,n){
> d<-seq(-1,1,by=0.001)
> .
> .
> .
> (SOME CALCULATIONS)
> .
> .
> .
> return(sprintf("%.5f",d[i-1]))
> }
>
> d is a vector with the numbers I need, specially the last one.
>
> how can I get the resulting number of the function with a certain amount of
> decimal places?
>
> Thanks.
>
> Liliana Pacheco
Presuming tat you want to be able to pass an argument that defines the number of
decimal places:
myfunc <- function(x, nsmall) {sprintf("%.*f", nsmall, x)}
> myfunc(3.123456, 3)
[1] "3.123"
> myfunc(3.123456, 5)
[1] "3.12346"
> myfunc(3.123456, 2)
[1] "3.12"
The argument 'nsmall' is passed to sprintf() and replaces the
'*' formatting parameter.
See the description towards the end of the Details in ?sprintf
HTH,
Marc Schwartz