[R] seeking advice about rounding error and %%

Paul Johnson pauljohn32 at gmail.com
Sat Aug 13 21:42:41 CEST 2011


A client came into our consulting center with some data that had been
damaged by somebody who opened it in MS Excel.  The columns were
supposed to be integer valued, 0 through 5, but some of the values
were mysteriously damaged. There were scores like 1.18329322 and such
in there.  Until he tracks down the original data and finds out what
went wrong, he wants to take all fractional valued scores and convert
to NA.

As a quick hack, I suggest an approach using %%

> x <- c(1,2,3,1.1,2.12131, 2.001)
> x %% 1
[1] 0.00000 0.00000 0.00000 0.10000 0.12131 0.00100
> which(x %% 1 > 0)
[1] 4 5 6
> xbad <- which(x %% 1 > 0)
>  x[xbad] <- NA
>  x
[1]  1  2  3 NA NA NA

I worry about whether x %% 1 may ever return a non zero result for an
integer because of rounding error.

Is there a recommended approach?

What about zapsmall on the left, but what on the right of >?

which( zapsmall(x %% 1) >  0 )


Thanks in advance

-- 
Paul E. Johnson
Professor, Political Science
1541 Lilac Lane, Room 504
University of Kansas



More information about the R-help mailing list