Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Truncate but NOT Round in R [duplicate]

Tags:

r

Really basic, but Googling didn't yield an answer. Is there a way to truncate a numeric value without rounding it?

For example:

vars <- c(23.4567, 45.6795, 34.5670)

I want the output to simply lob off the last two significant figures, but not round the output. What I want is:

vars <- c(23.45, 45.67, 34.56)

But the most common ways of doing this end up rounding (round, of course, but also signif:

round(vars, 2)

[1] 23.46 45.68 34.57

signif(vars, digits=4)

[1] 23.46 45.68 34.57

Please point me in the right direction if this has already been addressed here, but couldn't find it specific to R...

like image 860
Marc Tulla Avatar asked Aug 12 '15 12:08

Marc Tulla


2 Answers

You could try with floor()

vars <- floor(vars*100)/100

However, this solution assumes that all values are positive, as floor() rounds to the next lower integer. If there are negative numbers this approach could yield undesirable results:

> floor(-23.441*100)/100
#[1] -23.45

A more general solution therefore consists in using trunc():

vars <- trunc(vars*100)/100

This will remove any digit after the first two decimals, and it also works for negative numbers:

> trunc(-23.441*100)/100
#[1] -23.44
like image 50
RHertel Avatar answered Oct 20 '22 09:10

RHertel


You could use the floor() function, with a little extra help.

floor(100*vars)/100
like image 21
Jean V. Adams Avatar answered Oct 20 '22 08:10

Jean V. Adams