如何使用 'tables' 包在 R 中将 data.frame 写入 PDF table?

how to use the 'tables' package to write data.frame to PDF table in R?

我有一个数据框。例如,它看起来像这样:

Condition    dv1_mean    dv2_mean
A               1           2
A               2           3
A               2           3
B               3           4
B               3           4
B               3           4
C               3           4
C               3           4
C               3           4

我的代码如下:

stderr <- function(x) sd(x)/sqrt(length(x))

table<-toLatex(
  tabular( (Condition + 1) ~ (n=1) + Format(digits=2)*
            (dv1_mean + dv2_mean)*(mean + sd+median+stderr), data=accuracy ))

table

当我点击 knit PDF 时,我的代码输出是一堆未格式化的乱码,如下所示:

\begin{tabular}{lccccccccc}
\hline
 &  & \multicolumn{4}{c}{dv1_mean} & \multicolumn{4}{c}{dv2_mean} \ 
Condition  & n & mean & sd & median & stderr & mean & sd & median & \multicolumn{1}{c}{stderr} \ 
\hline
C1: Control  & $\phantom{0}433$ & $\phantom{-}0.015$ & $\phantom{-}0.487$ & $-0.172$ & $\phantom{-}0.023$ & $\phantom{-}0.022$ & $\phantom{-}0.595$ & $-0.199$ & $\phantom{-}0.029$ \
C2: Brier-Continuous  & $\phantom{0}423$ & $-0.063$ & $\phantom{-}0.452$ & $-0.243$ & $\phantom{-}0.022$ & $-0.142$ & $\phantom{-}0.532$ & $-0.339$ & $\phantom{-}0.026$ \
C3: Superforecaster  & $\phantom{00}17$ & $-0.306$ & $\phantom{-}0.129$ & $-0.309$ & $\phantom{-}0.031$ & $-0.266$ & $\phantom{-}0.346$ & $-0.354$ & $\phantom{-}0.084$ \
C4: Reciprocal-Continuous  & $\phantom{0}428$ & $-0.031$ & $\phantom{-}0.484$ & $-0.234$ & $\phantom{-}0.023$ & $-0.062$ & $\phantom{-}0.582$ & $-0.287$ & $\phantom{-}0.028$ \
All  & 01$ & $-0.030$ & $\phantom{-}0.474$ & $-0.215$ & $\phantom{-}0.013$ & $-0.063$ & $\phantom{-}0.572$ & $-0.280$ & $\phantom{-}0.016$ \
\hline 
\end{tabular}

如何正确使用 tables 包和 toLatex 函数?

您需要告诉 knitr 在处理输出时不要理会输出。为此,将 results="asis" 放入生成 table 的块中。例如,在 R Markdown 中:

---
title: "Untitled"
output: pdf_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```

`## R Markdown

This is an R Markdown document.

```{r results='asis'}
accuracy <- data.frame(Condition = factor(rep(c("A", "B", "C"), each = 3)),
                       dv1mean = c(1,2,2,3,3,3,3,3,3),
                       dv2mean = c(2,3,3,4,4,4,4,4,4))

stderr <- function(x) sd(x)/sqrt(length(x))

library(tables)

table<-toLatex(
  tabular( (Condition + 1) ~ (n=1) + Format(digits=2)*
            (dv1mean + dv2mean)*(mean + sd+median+stderr), data=accuracy ))

table
```

请注意,我做了一些其他更改:Condition 需要成为一个因素,名称 dv1_meandv2_mean 中的下划线会导致 Latex 出现问题,所以我删除了它们。您也可以使用 Heading 设置明确的列标题。例如,Heading("$dv_1$-mean")*dv1_mean 而不是 dv1_mean 会产生