指数为10

时间:2015-03-30 09:37:17

标签: r knitr

我想出了这个UDF,必须有更好的方法吗?

如果数字为<0.00001,则使用基数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

enter image description here

2 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:1)

这是一个带有(多个)gsub的命题,它有所不同,但我怀疑你能说它是“更好的方式”......

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"