[R] Digits in R

Duncan Murdoch murdoch.duncan at gmail.com
Tue Mar 25 15:04:19 CET 2014


On 25/03/2014 7:17 AM, Pavneet Arora wrote:
> Hello All,
>
> I am new in R, so please excuse the basic questions.
> But how do you change the number of digits to be displayed?
>
> I have done the following, hoping I will get 4 decimal places in my
> answer:
>
> vars <- var(cbind(Sepal.l,Sepal.w,Petal.l,Petal.w))
> print(vars,digits=4)
>
> But as seen below from the output, that is not the case
>
> > print(vars,digits=4)
>           Sepal.l  Sepal.w Petal.l Petal.w
> Sepal.l  0.68569 -0.04074  1.2743  0.5163
> Sepal.w -0.04074  0.19363 -0.3287 -0.1212
> Petal.l  1.27432 -0.32873  3.1163  1.2956
> Petal.w  0.51627 -0.12124  1.2956  0.5810
>
> How come the Sepal.l and Sepal.w does not come with only 4 decimal places.

R interprets "digits=4" as asking for 4 significant digits. The value 
0.04074 needs 5 decimal places to get 4 significant digits. R will print 
all numbers in a column with a consistent number of decimal places, so 
all values get 5.


> Can someone tell me where I am going wrong?
>
> Also if I use the "options(digits=4)"- How do I make it to go back to
> Normal or default, which is 7 in this case.?

Save it when you change it, and restore it afterwards, e.g.

saveopts <- options(digits=4)
... do some stuff ...
options(saveopts)

This doesn't restore the default, it restores the previous value, but 
that's usually what you want. If you really want to restore the default, 
then save it at the very beginning of your session, e.g.

defaultopts <- options() # save all options

... do some stuff ...

options(defaultopts) # restore all options
options(defaultopts["digits"]) # restore just the digits setting

Duncan Murdoch
> ***********************************************************************************************************************************************************************************************************************
> MORE TH>N is a trading style of Royal & Sun Alliance Insurance plc (No. 93792). Registered in England and Wales at St. Mark’s Court, Chart Way, Horsham, West Sussex, RH12 1XL.
>
> Authorised by the Prudential Regulation Authority and regulated by the Financial Conduct Authority and the Prudential Regulation Authority.
> ************************************************************************************************************************************************************************************************************************
>
> 	[[alternative HTML version deleted]]
>
>
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.




More information about the R-help mailing list