繁体   English   中英

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

[英]How to create and export a Matrix (after analysis) as a Table using r and 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时,我只是得到一堆代码作为输出。

我觉得我在这里错过了一些非常简单的事情。 也许我需要将Latex添加到我的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中的“编织”按钮或rmarkdown::render函数将此文件转换为不同的输出格式(HTML,PDF,DOCX)。 先决条件:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM