knitr 内联块中的公式输出

Formula output in knitr inline chunk

我想用 knitr 写一篇可重现的社会科学论文。所以我想使用 knitr 内联块打印内联验证性因素分析的拟合指数。

我的最小示例:

\documentclass{article}

\begin{document}

Run a lavaan model

<<lavaanmodel>>=
library(lavaan)
## cfa model from help
HS.model <- ' visual  =~ x1 + x2 + x3
              textual =~ x4 + x5 + x6
              speed   =~ x7 + x8 + x9 '

cfaout <- cfa(HS.model, data=HolzingerSwineford1939)
@

Specifiy a fitprintfunction

<<fpf_def>>=
fpf_la <- function(x){  fm_tmp <- fitmeasures(x)

                        cat("\chi^2 = ", fm_tmp[c("chisq")],
                            ", df = ",    fm_tmp[c("df")],
                            ", RMSEA = ", fm_tmp[c("rmsea")],
                            ", CFI = ",   fm_tmp[c("cli")],
                            ", TLI = ",   fm_tmp[c("tli")],
                            ", SRMR = ",  fm_tmp[c("srmr")],
                            sep = "")}
@

Print the fit inline:\

The specified model resulted in good model fit $\Sexpr{fpf_la(cfaout)}$

\end{document}

问题:$\Sexpr{fpf_la(cfaout)}$ 没有结果。 我猜想处理内联块中的非数字输出会导致问题?

\Sexpr中使用的函数应该return输出。你的功能打印它。

最小示例:

\documentclass{article}
\begin{document}
<<>>=
showSquare <- function(x) {
  return(sprintf("%s^2 = %s", x, x^2))
}
@

Let's square 42: $\Sexpr{showSquare(42)}$.

\end{document}