一个使用siunitx的例子,pdf链接。在导言部分,您可以定义默认选项,稍后可以在文档中覆盖这些选项。
对于数字输出:
num <- function(x,round_precision=NULL)
{
if (is.null(round_precision)) {
return(sprintf("\\num{%s}", x))
} else {
return(sprintf("\\num[round-precision=%s]{%s}",round_precision, x))
}
}
科学输出:
sci<- function(x,round_precision=NULL){
if (is.null(round_precision)) {
return(sprintf("\\num[scientific-notation = true]{%s}", x))
} else {
return(sprintf("\\num[round-precision=%s,scientific-notation = true]{%s}",round_precision, x))
}
}
![siunitx example](https://istack.dev59.com/PMHlT.webp)
这里是一个完整可复制的.Rnw脚本(要与knitr一起使用...对于sweave,请在函数中使用四个反斜杠而不是两个,参见此SO post。)
\documentclass[a4paper]{article}
\usepackage{siunitx}
\title{siunitx}
\sisetup{
round-mode = figures,
round-precision = 3,
group-separator = \text{~}
}
\begin{document}
\maketitle
<<sanitize_number,echo=FALSE>>=
num <- function(x,round_precision=NULL)
{
if (is.null(round_precision)) {
return(sprintf("\\num{
} else {
return(sprintf("\\num[round-precision=
}
}
sci<- function(x,round_precision=NULL){
if (is.null(round_precision)) {
return(sprintf("\\num[scientific-notation = true]{
} else {
return(sprintf("\\num[round-precision=
}
}
@
Examples :\\
$num$ for number formatting :
\begin{itemize}
\item \textbf{num(pi, round\_precision=2)} $\Rightarrow$
\num[round-precision=2]{3.14159265358979}
\item \textbf{num(pi, round\_precision=4)} $\Rightarrow$
\num[round-precision=4]{3.14159265358979}
\item The default formatting (here round-precision=3) is taken from
\textbf{\textbackslash sisetup}
\textbf{num(pi)} $\Rightarrow$ \num{3.14159265358979}\\
\end{itemize}
\noindent $sci$ for scientific notation :
\begin{itemize}
\item \textbf{sci(12.5687e4)} $\Rightarrow$ \num[scientific-notation =
true]{125687}
\item \textbf{sci(125687.11111)} $\Rightarrow$
\num[scientific-notation = true]{125687.11111}
\item \textbf{sci(125687.11111, round\_precision=4)} $\Rightarrow$
\Sexpr{sci(125687.11111, round_precision=4)}
\end{itemize}
\end{document}