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

______________________________________________
R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
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.

Reply via email to