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.
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.
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) } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With