在mathematica
中,我们有RealDigits可以识别小数点和整数值的第一个非零数。下面是一个例子:
RealDigits[ 0.00318, 10, 1]
{{3},-2}
RealDigits[ 419, 10, 1]
{{4},-2}
在上面的例子中,函数识别0.00318和419时分别为3和4。
R
中有没有类似的函数?
发布于 2020-11-11 21:08:27
你可以这样做:
x <- c(0.0000318, 419)
as.numeric(substr(formatC(x, format = 'e'), 1, 1))
# [1] 3 4
发布于 2020-11-11 21:34:24
此函数将接受向量参数以及depth
参数,该参数允许您定义在第一个有效数字之后要有多少位数字。
x <- c(0.00318, 0.000489, 895.12)
RealDigits <- function(x, depth=1) {
y <- as.character(x)
ysplit <- strsplit(y,"")
ysplit <- strsplit(y,"")
last0 <- lapply(ysplit, function(x) tail(which(x==0),1))
last00 <- sapply(last0, function(x) if (length(x) ==0) 0 else x )
res <- substr(y, last00+1, as.numeric(sapply(y, nchar)))
return(substr(res, 0,depth))
}
RealDigits(x)
RealDigits(x, depth =2)
> RealDigits(x)
[1] "3" "4" "8"
> RealDigits(x, depth =2)
[1] "31" "48" "89"
https://stackoverflow.com/questions/64794028
复制