Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rounding numbers to nearest 10 in R

Tags:

r

Now, there has been some very similar questions on SO about rounding and significance, but non solves my issue. Here it is:

How to round randomly occurring numbers like these:

data <- c(152.335, 39.431, 21.894)

I would like to have them rounded like this:

c(150,40,20)

I have tried:

print(formatC(signif(data,digits=2), digits=2,format="f"))

Output:

[1] "150.00" "39.00"  "22.00"

The above command requires me to change the digits= to 1 or 2 in order to obtain the desired outcome. But, I would like a global - fit for all command. Thanks.

like image 442
Maximilian Avatar asked Aug 28 '13 15:08

Maximilian


Video Answer


2 Answers

From ?round

Rounding to a negative number of digits means rounding to a power of ten, so for example ‘round(x, digits = -2)’ rounds to the nearest hundred.

So,

data <- c(152.335, 39.431, 21.894)
round(data, -1)
#[1] 150  40  20
like image 59
GSee Avatar answered Oct 14 '22 17:10

GSee


You actually want a different argument for signif here. This seems to do the trick -- 2 digits for first argument, one for the last two:

R> dat <- c(152.335, 39.431, 21.894)
R> dat
[1] 152.335  39.431  21.894
R> signif(dat, digits=c(2,1,1))
[1] 150  40  20
R> 

You can possibly generalize this via something like

R> signif(dat, digits=floor(log10(dat)))
[1] 150  40  20
R> 
like image 41
Dirk Eddelbuettel Avatar answered Oct 14 '22 15:10

Dirk Eddelbuettel