捕获多个命令的控制台输出并写入 txt

capture console output of multiple commands and write to txt

我知道 sink()capture.output()。不知何故我无法得到我想要的结果。

我的代码块示例

mtcars[1:2,1:2]
#this is awesome,
mtcars[1:2,1:2] %>% rowMeans(.)

我的 txt 文件中的所需输出:必须与我的控制台中的外观 100% 相似:

> mtcars[1:2,1:2]
              mpg cyl
Mazda RX4      21   6
Mazda RX4 Wag  21   6
>     #this is awesome,
>     mtcars[1:2,1:2] %>% rowMeans(.)
    Mazda RX4 Mazda RX4 Wag 
         13.5          13.5

伪代码

如果有这样的东西就好了:

console2txt(file="text.txt")
    mtcars[1:2,1:2]
    #this is awesome,
    mtcars[1:2,1:2] %>% rowMeans(.)
dev.off()

是否有捕获“脚本块”的整个控制台的解决方案。

通常我用 RMarkdown.

---
output: rtf_document
---
```{r}
mtcars[1:2,1:2]
#this is awesome,
mtcars[1:2,1:2] %>% rowMeans(.)
```