我在R.工作.我有十进制度的一系列坐标,我想按这些数字的小数位数排序这些坐标(即我想丢弃小数位数太少的坐标).
R中是否有一个函数可以返回一个数字所具有的小数位数,我可以将其合并到函数编写中?
输入示例:
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
Run Code Online (Sandbox Code Playgroud)
理想情况下,我会编写一个废弃AniLac9和AniLac 5的脚本,因为这些坐标没有以足够的精度记录.我想丢弃经度和纬度都少于3个非零十进制值的坐标.
dar*_*zig 27
您可以轻松地为任务编写一个小函数,例如:
decimalplaces <- function(x) {
if ((x %% 1) != 0) {
nchar(strsplit(sub('0+$', '', as.character(x)), ".", fixed=TRUE)[[1]][[2]])
} else {
return(0)
}
}
Run Code Online (Sandbox Code Playgroud)
并运行:
> decimalplaces(23.43234525)
[1] 8
> decimalplaces(334.3410000000000000)
[1] 3
> decimalplaces(2.000)
[1] 0
Run Code Online (Sandbox Code Playgroud)
更新(2018年4月3日)以解决@ owen88关于因舍入双精度浮点数而导致错误的报告 - 替换x %% 1检查:
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)
}
}
Run Code Online (Sandbox Code Playgroud)
J. *_*in. 10
这是一种方式.它会检查小数点后的前20个位置,但如果您有其他想法,则可以调整数字20.
x <- pi
match(TRUE, round(x, 1:20) == x)
Run Code Online (Sandbox Code Playgroud)
这是另一种方式.
nchar(strsplit(as.character(x), "\\.")[[1]][2])
Run Code Online (Sandbox Code Playgroud)
罗马的建议:
num.decimals <- function(x) {
stopifnot(class(x)=="numeric")
x <- sub("0+$","",x)
x <- sub("^.+[.]","",x)
nchar(x)
}
x <- "5.2300000"
num.decimals(x)
Run Code Online (Sandbox Code Playgroud)
如果您的数据不保证是正确的形式,您应该做更多检查以确保其他角色不会偷偷摸摸.