如何在 RMarkdown 内联代码中编写正确的表达式

How to write the right expression in RMarkdown inline code

我想将 k-s 测试的结果与使用 RMarkdown 的内联代码结合使用。我可以得到 ks$statistic[[1]]ks$p.value[[1]] 但是当我内联使用它们时,我得到一个错误。

---
title: "ks test2"
output:
  word_document: default
---

```{r setup, include=FALSE}
library(knitr)
knitr::opts_chunk$set(echo = TRUE, results="asis")
```{r echo=FALSE}
x <- rnorm(50)
ks <- ks.test(x, "pnorm", mean=mean(x),
        sd=sd(x))
df <- length(x)
```

Based on K-S test (`r D (df) = ks$statistic[[1]], p = ks$p.value[[1]]`), we can conlude something.

您的内联代码不是有效的 R 代码。尝试这样的事情:

```{r, echo=FALSE}
x <- rnorm(50)
ks <- ks.test(x, "pnorm", mean=mean(x), sd=sd(x))
df <- length(x)
```

Based on K-S test (D(`r df`) = `r ks$statistic[[1]]`, p = `r ks$p.value[[1]]`), we can conlude something.

但您可能希望格式化这些数字以进行打印,因此您可以尝试更像这样的操作:

Based on K-S test (D(`r df`) = `r format(round(ks$statistic[[1]], 2), nsmall = 2)`, p = `r format(round(ks$p.value[[1]], 2), nsmall = 2)`), we can conlude something.