如何使用 r 和 Latex 创建矩阵(分析后)并将其导出为表?



我已经完成了我的分析。我的最终输出是矩阵,即使有行和列名。 现在我只需要制作一个漂亮的带有线条的表格并将其输出为(可能是pdf(或(可能像可编辑的word文件(。

我做了自己的研究,发现有很多软件包,比如xtable和knitr。但是当我安装这些包并执行代码时。我只是得到一堆代码作为输出。

mat <- matrix(c(1:91), ncol = 7, byrow=F)
rownames(mat) <- c("Y1","Y2","Y3","Y4","Y5","Y6","Y7","Y8","Y9","Y10", 
"Y11", "Y12", "Total water")
colnames(mat) <- c("Runoff", "RM", "DEEP Percolation", "ET", 
"Lateralflow", "Change in SW", "Change in FW")
mat
library(knitr)
kable(mat)
library(xtable)
xtable(mat, type="latex")

当我使用 kable 时,我得到了一个表格,但我没有得到格式化的表格(就像你可以用文字制作的那样(。当我使用 xtable 时,我只是得到一堆代码作为输出。

我觉得我在这里错过了一些非常简单的东西。也许我需要将乳胶添加到我的 R 中?这样当我运行代码时,我将获得表而不是代码作为输出。

如果有人能把我推向正确的方向,我将不胜感激。 或者任何简单的解决方案也会有所帮助。

我不知道一种简单的方法可以将矩阵或data.frame格式化为PDF或类似表格,就像您可以对绘图所做的那样。但是,您可以轻松地使用 R Markdown 创建整个报表,包括具有嵌入式 R 代码的表和绘图。这样,您就不必首先为导出绘图或表格而烦恼。以下示例使用您的代码扩展了 RStudio 创建的默认Rmd文件:

---
title: "My Analysis"
author: "Samrat"
date: "`r Sys.Date()`"
output:
html_document: default
pdf_document: default
word_document: default
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
## R Markdown
This is an R Markdown document. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. For more details on using R Markdown see <http://rmarkdown.rstudio.com>.
When you click the **Knit** button a document will be generated that includes both content as well as the output of any embedded R code chunks within the document. You can embed an R code chunk like this:
```{r cars}
summary(cars)
```
## Including Plots
You can also embed plots, for example:
```{r pressure, echo=FALSE}
plot(pressure)
```
Note that the `echo = FALSE` parameter was added to the code chunk to prevent printing of the R code that generated the plot.
## Including Tables
If you have tabular data as `matrix` or `data.frame` you can output it in a nicely formatted way. First the "analysis" that produces the data:
```{r analysis}
mat <- matrix(c(1:91), ncol = 7, byrow=F)
rownames(mat) <- c("Y1","Y2","Y3","Y4","Y5","Y6","Y7","Y8","Y9","Y10", 
"Y11", "Y12", "Total water")
colnames(mat) <- c("Runoff", "RM", "DEEP Percolation", "ET", 
"Lateralflow", "Change in SW", "Change in FW")
```
Now we print the data as a table:
```{r table, echo=FALSE}
library(knitr)
kable(mat)
```

您可以通过RStudio中的"Knit"按钮或rmarkdown::render功能将此文件转换为不同的输出格式(HTML,PDF,DOCX(。先决条件:

  • 来自 CRAN 的rmarkdown
  • pandoc程序,自带RStudio
  • 对于PDF输出,您将需要一个TeX系统。在许多情况下,最简单的方法是从 Rtinytex::install_tinytex()

最新更新