knitr tables appear as one long column

北慕城南 提交于 2019-12-11 17:06:15

问题


I pretty much copied word-for-word the example from this site on how to create multiple PDFs in knitr from one for-loop: http://www.reed.edu/data-at-reed/software/R/markdown_multiple_reports.html

When I try calling knitr::kable(cars) or kable(cars) the output of each PDF appears as one long column instead of an actual table, as shown in the photo.

Any idea what causes this? Here's the .R and the .Rmd code called in each iteration of the loop:

.R

library(knitr)
library(markdown)
library(rmarkdown)
mt <- mtcars[1:5,]
for (car in unique(rownames(mt))){
     rmarkdown::render('test.Rmd',
                output_format = "pdf_document",
                output_file =  paste(car, ' report.pdf', sep=''), 
                output_dir = '~/')

test.Rmd

library(knitr)
library(markdown)
library(rmarkdown)
cars <- mtcars[rownames(mtcars)==car,]

# create example data 
x <- sample(1:10, 1)
cars <- do.call("rbind", replicate(x, cars, simplify = FALSE))

# create hypothetical lat and lon data 
cars$lat <- sapply(rownames(cars), function(x) round(runif(1, 30, 46), 3))
cars$lon <- sapply(rownames(cars), function(x) round(runif(1, -115, -80),3))
knitr::kable(cars)
kable(cars)

I was able to get are relatively normal looking table by using kable(cars, format = "latex")

I was hoping to get some quick and decent html tables, and now when I try to format in LaTeX with something like kable(cars, format = "latex", booktabs = T), I get this error:

pandoc: Error producing PDF
Error: pandoc document conversion failed with error 43

回答1:


You have to modify the .Rmd file to include the package in output Create a YAML header with

header-includes:
   - \usepackage{booktabs}

modified .Rmd file which now works for me (I was also reproducing your error)

---
title: "Title"
author: "Me"
header-includes:
   - \usepackage{booktabs}
output:
    pdf_document
---
```{r kable}
library(knitr) 
library(markdown)
library(rmarkdown) 
cars <-mtcars[rownames(mtcars)==car,]

# create example data 
x <- sample(1:10, 1) 
cars <- do.call("rbind", replicate(x, cars, simplify =FALSE))

# create hypothetical lat and lon data 
cars$lat <- sapply(rownames(cars), function(x) round(runif(1, 30, 46), 3))
cars$lon <-sapply(rownames(cars), function(x) round(runif(1, -115, -80),3))
knitr::kable(cars, format = "latex", booktabs = T)
```

Now this produces four files



来源:https://stackoverflow.com/questions/47602105/knitr-tables-appear-as-one-long-column

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!