Curious rounding in R

Sometimes R has a misleading way of displaying values.  Check out this series of commands:

> 1111+.5
[1] 1111.5
> 11111+.5
[1] 11111.5
> 111111+.5
[1] 111111.5
> 1111111+.5
[1] 1111112
> 11111111+.5
[1] 11111112

At first I thought that R was automatically rounding the numbers.  So the value got changed if it exceeded certain number of digits.  But in reality R know the real value; it just chooses to display it differently.  To prove this I executed this series of commands:

> a = 1111111 + .5
> a
[1] 1111112
> a == 1111111.5
[1] TRUE

Notice that the value of ‘a’ is not 1111112 but 11111111.5.  I kept on looking and found out that you can modify the way R displays the numbers.  You just need to modify the global variable digits.  This will modify the way numbers are displayed for the rest of the R session.

options(digits=15)

But notice that even though you change the digits option, you don’t change the values themselves.

Advertisements

About joelgranados

I'm fascinated with how technology and science impact our reality and am drawn to leverage them in order to increase the potential of human activity.
This entry was posted in commands, PhD, R. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s