[R] How to force R to print 2 decimal places in column of a data.frame?

Marc Schwartz marc_schwartz at me.com
Thu Jun 11 20:45:07 CEST 2009


On Jun 11, 2009, at 11:48 AM, Lesandro wrote:

>
> How to force R to print 2 decimal places in column of a data.frame?  
> I tried to do so:
>
> x = inp(format(rounf(inp$Tamanho, 2), nsmall = 2),)
>
> where "INP" is data.frame and "Size" is the name of column. But has  
> error:
>
> Error in eval.with.vis(expr, envir, enclos) :
>  could not find function "inp"
>
> Lesandro



Your code and description above appear to have some typos in it and  
the use of the round() and format() functions are not what you want  
here.

You code has inp(...), where R is presuming that you are referring to  
a function called 'inp', hence the error message, since the function  
does not exist.

Better to use sprintf() with an appropriate format specifier:

set.seed(1)
vec <- rnorm(10)

 > vec
  [1] -0.6264538  0.1836433 -0.8356286  1.5952808  0.3295078 -0.8204684
  [7]  0.4874291  0.7383247  0.5757814 -0.3053884

 > sprintf("%.2f", vec)
  [1] "-0.63" "0.18"  "-0.84" "1.60"  "0.33"  "-0.82" "0.49"  "0.74"
  [9] "0.58"  "-0.31"

See ?sprintf for more information.  Note that the presumption here is  
that you want to output the numeric values to a formatted character  
vector for display purposes, perhaps in a table, etc.

So if your actual data frame is called 'INP' and the column is called  
'Size', you would use:

   sprintf("%.2f", INP$Size)


HTH,

Marc Schwartz




More information about the R-help mailing list