[R] A small thing that amused my small mind

Bert Gunter bgunter@4567 @end|ng |rom gm@||@com
Thu Sep 6 04:28:31 CEST 2018


A few days ago, someone asked how to truncate arbitrary numerics to 1
digit towards 0. e.g. -189 should become -100 and 254 should become
200; and all values in magniude < 1 should become 0.

I proposed a somewhat clumsy solution using floor() and ceiling(), but
in fooling with it a bit more, I realized that a better way to do it
is to use R's trunc() function. It is simpler and works for all cases
AFAICS. Here's a litte function to do it -- maybe someone else might
find it amusing/instructive:

poof <- function(x){
   ## truncating to 0
## x is a numeric vector
k <- 10^trunc(log10(abs(x)))
ifelse(k, trunc(x/k)*k, k)
}

## test it
> x <- c(0,-.036578, .4876, -189, 254)
> poof(x)
[1]    0    0    0 -100  200

Cheers,
Bert




More information about the R-help mailing list