[R] Difficult with round() function
Petr Savicky
savicky at praha1.ff.cuni.cz
Tue Jan 18 09:33:19 CET 2011
On Mon, Jan 17, 2011 at 12:02:21PM -0800, Aaron Polhamus wrote:
> Dear list,
>
> I'm writing a function to re-grid a data set from finer to coarser
> resolutions in R as follows (I use this function with sapply/apply):
>
> gridResize <- function(startVec = stop("What's your input vector"),
> to = stop("Missing 'to': How long do you want the fnial vector to be?")){
> from <- length(startVec)
> shortVec<-numeric()
> tics <- from*to
> for(j in 1:to){
> interval <- ((j/to)*tics - (1/to)*tics + 1):((j/to)*tics)
The vector "interval" computed as above may contain non-integer values,
because of rounding error. For example,
to <- 200
from <- 300
tics <- from*to
j <- c(27, 54, 107, 108, 109)
(j/to)*tics - j*from
# [1] 9.094947e-13 1.818989e-12 3.637979e-12 3.637979e-12 3.637979e-12
Since "tics" is a multiple of "to", the expression may be rearranged as
interval <- (j*from - from + 1):(j*from)
and then it only contains integers.
> benchmarks <- interval/to
> #FIRST RUN ASSUMES FINAL BENCHMARK/TO IS AN INTEGER...
> positions <- which(round(benchmarks) == benchmarks)
If the above modification of "interval" is used, then "benchmarks" is obtained
as a result of a division of two integers. In this situation, this test is
correct, since a single division, whose exact result is an integer, produces
an integer also in double precision.
Alternatively, the test for integer "benchmarks" may be done by testing
divisibility of "interval" by "to", for example
which(interval %% to == 0)
> indeces <- benchmarks[positions]
> fracs <- numeric()
> #SINCE MUCH OF THE TIME THIS WILL NOT BE THE CASE, THIS SCRIPT DEALS WITH
> THE REMAINDER...
> for(i in 1:length(positions)){
If "positions" may, in some situations, be of length 0, then it
is better to use
for(i in seq(along=positions))
or
for(i in seq(length=length(positions)))
For zero length "positions", 1:length(positions) is 1:0, which is of
length 2. The expressions seq(along=positions) and seq(length=length(positions))
are integer(0) in this situation.
Petr Savicky.
More information about the R-help
mailing list