[R] number of decimal places in a number?

Martin Ivanov tramni at abv.bg
Sat Jul 7 15:52:41 CEST 2012


 Dear Mr Harding,

Thank You very much for Your responsiveness.

 >There would seem to be no clean general solution to this
 >question. An important issue would be: What use do you
 >want to put the result to?
 
I need this trick for the following task.
I am writing a function which has to determine the bounding box for a 
spatial data set. The bounding box is a matrix(c(minLon minLat, maxLon, maxLat)).
I have the longitudes (lon) and latitudes (lat), and I have a resolution (r), for example 
r = 0.004. The bounding box must have the same number of digits as resolution. 
So I first have to truncate min(lon) and min(lat) to 3 decimal places,
then take the ceiling of max(lat)*10^3 and max(lon)*10^3 divided by 10^3. So I have the 
maximal interval with resolution r for each variable (lat or lon). Then I have to determine
the number of cells in each direction, which I take as ceiling((maxLat-minLat)/r) and
ceiling((maxLon-minLon)/r). Here is an example of my code:

 # get the first n digits from a number
truncf <- function(x, digits) {
 # some control:
 for(i in c("x", "digits")) if(!(is.numeric(get(i)) && length(get(i)) == 1)) stop(i, " in truncatef must be a  numeric scalar!");
 ## make sure that digits is an integer:
 if(as.integer(digits) - digits) stop("Please provide an integer digits to truncf!");

 x <- trunc(x*10^digits)/10^digits;
 x;
}
 for(i in 0:5) if(!(resolution*10^i - as.integer(resolution*10^i))) break;
 lonMin <- truncf(x=min(lon), digits=i); lonMax <- ceiling(x=max(lon)*10^i)/10^i;
 latMin <- truncf(min(lat), digits=i); latMax <- ceiling(x=max(lat)*10^i)/10^i;
 cells.dim <- ceiling(c(lonMax - lonMin, latMax - latMin)/resolution);
 
 
I hope this sheds more light on my issue.

Best regards,
Martin

-----------------------------------------------------------------
Гражданска отговорност – Цените на компаниите
http://www.sdi.bg/onlineInsurance/?utm_source=gbg&utm_medium=txtLink&utm_content=home



More information about the R-help mailing list