Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to return number of decimal places in R

Tags:

I am working in R. I have a series of coordinates in decimal degrees, and I would like to sort these coordinates by how many decimal places these numbers have (i.e. I will want to discard coordinates that have too few decimal places).
Is there a function in R that can return the number of decimal places a number has, that I would be able to incorporate into function writing?
Example of input:

AniSom4     -17.23300000        -65.81700  AniSom5     -18.15000000        -63.86700  AniSom6       1.42444444        -75.86972  AniSom7       2.41700000        -76.81700  AniLac9       8.6000000        -71.15000  AniLac5      -0.4000000        -78.00000 

I would ideally write a script that would discard AniLac9 and AniLac 5 because those coordinates were not recorded with enough precision. I would like to discard coordinates for which both the longitude and the latitude have fewer than 3 non-zero decimal values.

like image 442
Pascal Avatar asked Mar 02 '11 21:03

Pascal


People also ask

How do you round to 2 decimal places in R?

You can use the following functions to round numbers in R: round(x, digits = 0): Rounds values to specified number of decimal places. signif(x, digits = 6): Rounds values to specified number of significant digits.


1 Answers

You could write a small function for the task with ease, e.g.:

decimalplaces <- function(x) {     if ((x %% 1) != 0) {         nchar(strsplit(sub('0+$', '', as.character(x)), ".", fixed=TRUE)[[1]][[2]])     } else {         return(0)     } } 

And run:

> decimalplaces(23.43234525) [1] 8 > decimalplaces(334.3410000000000000) [1] 3 > decimalplaces(2.000) [1] 0 

Update (Apr 3, 2018) to address @owen88's report on error due to rounding double precision floating point numbers -- replacing the x %% 1 check:

decimalplaces <- function(x) {     if (abs(x - round(x)) > .Machine$double.eps^0.5) {         nchar(strsplit(sub('0+$', '', as.character(x)), ".", fixed = TRUE)[[1]][[2]])     } else {         return(0)     } } 
like image 137
daroczig Avatar answered Sep 28 '22 03:09

daroczig