我可以在 R/exams 中将 pstricks 代码包含在 exams2pdf 和 exams2moodle 输出中吗?

Can I include pstricks code in R/exams with exams2pdf and exams2moodle output?

我正在尝试将以下 pstricks 代码片段包含在 R/exams.Rmd 练习中,但我不知道该怎么做:

\begin{pspicture}(-2, -2)(3, 3)
\psset{viewpoint=100 30 20,Decran=100}
\psSolid[object=cube, a=2,
    action=draw*,
    fillcolor = magenta!20
]
\axesIIID[showOrigin=false, labelsep=5pt](1,1,1)(3,2,2)
\end{pspicture}

\begin{tikzpicture}
    \draw[<->] (0, 0) -- (5, 5);
\end{tikzpicture}

是的,这是可能的,尽管我不推荐它。您可以使用以下内容:

  • 设置一个包含 pstricks 的 LaTeX 代码的字符串。
  • 调用 tex2image(..., packages = c("auto-pst-pdf", ...)) 以便使用 LaTeX 包 {auto-pst-pdf}。这支持在 pdfLaTeX 的文档中嵌入 pstricks,通过在后台为图形调用 LaTeX。
  • 确保 tex2image() 使用 -shell-escape 选项调用 pdfLaTeX,以便允许 pdfLaTeX 调用 LaTeX。使用 R 包 tinytex.
  • 相对容易

下面包含此策略的一个有效示例,称为 dist4.Rmd。如果您将 R/Markdown 代码复制到文件中,您可以 运行:

exams2html("dist4.Rmd")

exams2moodle() 中也可以这样做。该练习的灵感来自 R/exams 中现成的 dist, dist2, dist3 练习模板。与这些在 R 中绘制图形的模板相比,dist4.Rmd 练习非常慢。 R 调用 pdfLaTeX,pdfLaTeX 调用 LaTeX,所有这些 post- 处理图形输出。因此,如果我在 pstricks 中有复杂的遗留 LaTeX 代码或在 pstricks 之上构建的专用包很难在 R(或 TikZ)中重写,我只会使用 pstricks。

下面是 R/Markdown 源代码。这类似于使用 include_tikz() 的练习。关键区别在于 (a) tex2image() 被直接调用(而不是通过 include_tikz()),(b) 生成的图像必须手动嵌入,以及 (c) R 包 tinytex 并且需要设置选项 tinytex.engine_args = "-shell-escape"

```{r, include = FALSE}
## data
p <- c(sample(1:3, 1), sample(1:5, 1))
q <- c(sample((p[1] + 1):5, 1), sample(1:5, 1))
sol <- sum(abs(p - q))

## pstricks
pst <- '
\begin{pspicture}(-1,-1)(7,7)  
\psaxes{->}(0,0)(-0.2,-0.2)(6.5,6.5)[$x$,0][$y$, 90]
\psdot(%s,%s)
\uput[0](%s,%s){$p$}
\psdot(%s,%s)
\uput[0](%s,%s){$q$}
\end{pspicture}
'
pst <- sprintf(pst, p[1], p[2], p[1], p[2], q[1], q[2], q[1], q[2])

## generate figure via tinytex and shell-escape option
opt <- options(exams_tex = "tinytex", tinytex.engine_args = "-shell-escape")
fig <- tex2image(pst, packages = c("auto-pst-pdf", "pst-all"),
  name = "pqdist", dir = ".", resize = 400)
options(opt)
```

Question
========

What is the Manhattan distance $d_1(p, q)$ of the two points
$p$ and $q$ shown in the following figure?

![](`r basename(fig)`)


Solution
========

The Manhattan distance is given by:
$d_1(p, q) = \sum_i |p_i - q_i| = |`r p[1]` - `r q[1]`| + |`r p[2]` - `r q[2]`| = `r sol`$.


Meta-information
================
exname: Manhattan distance
extype: num
exsolution: `r sol`
exclozetype: num