获取R中的第一个非零数字,类似于Mathematica

问题描述

mathematica中,我们有RealDigits可以为带小数点和整数的数字标识第一个非零数字。参见以下示例:

RealDigits[ 0.00318,10,1]
{{3},-2}
RealDigits[ 419,1]
{{4},-2}

在上面的示例中,该函数分别为0.00318和419标识3和4。

R中是否有类似的功能

解决方法

您可以这样做:

x <- c(0.0000318,419)

as.numeric(substr(formatC(x,format = 'e'),1,1))
# [1] 3 4
,

此函数将接受向量参数以及一个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,depth))
}
RealDigits(x)
RealDigits(x,depth =2)

> RealDigits(x)
[1] "3" "4" "8"
> RealDigits(x,depth =2)
[1] "31" "48" "89"