以 10 为底的指数

Exponential to base 10

这个UDF是我想出来的,一定有更好的方法吧?

如果数字是 <0.00001,则使用 base 10 表示法而不是 e-。输入范围是 0-1.

report.Rmd

```{r temp}
udf_expTo10 <- function(x){

  x <- as.character(x)

  if(grepl("e-",x)){
    x <- round(as.numeric(unlist(strsplit(x,"e-"))),1)
    x <- paste0(x[1]," x 10^-",x[2],"^")}else{
      x <- round(as.numeric(x),4)}

  return(as.character(x))
  }

```

pvalue = `r udf_expTo10(0.000000123)`

pvalue = `r udf_expTo10(0.00123)`

pvalue = `r udf_expTo10(1)`

pvlaue = `r udf_expTo10("-1.222123e-15")`

report.docx

这是一个带有(多个)gsub 的命题,它是不同的,但我怀疑你能说它是 "a better way"...

expTo10_bis <- function(x) {

   # beginning is the same as yours
   x <- as.character(x)

   if(grepl("e-", x)){
        # now the gsub "parade":
        x <- gsub("e", " x 10^", gsub("(?<=e-)0", "", x, perl=T))
        x <- gsub("-*\d\.\d+", round(as.numeric(gsub("([\S]*)\sx\s10.*$", "\1", x, perl=T)), 1), x, perl=T)

   } else { # end is same as yours
        x <- as.character(round(as.numeric(x), 4))
   }

   return(x)
}

expTo10_bis(0.0000023456) # "2.3 x 10^-6"
expTo10_bis(0.0123456) # "0.0123"
# and if you really want to test negative values:
expTo10_bis(-0.00000000000000000000000000789456) # "-7.9 x 10^-27"

这在knitr很久以前就已经完成了,你可以简单地写$`r -1.222123e-15`$$`r 0.000000123`$。我不确定您为什么要重新发明轮子,但我愿意接受改进建议 knitr:::format_sci_one