
我想使用 TeX 排版基於 R 物件(資料幀)中的資料的報告。這個想法是從 R 資料幀的每一行列印一個漂亮的 TeX 表。
就像是
\begin{tabular}{ l c r }
A1 & B1 & C1 \\
\end{tabular}
\begin{tabular}{ l c r }
A2 & B2 & C2 \\
\end{tabular}
\begin{tabular}{ l c r }
A3 & B3 & C3 \\
\end{tabular}
請考慮以下 MWE
\documentclass{article}
\begin{document}
<<prepare data>>=
one <- c("A1","B1","C1")
two <- c("A2","B2","C2")
three <- c("A3","B3","C3")
df <- data.frame(one,two,three)
@
<<loop data>>=
for (i in 1:nrow(df)) {
print(df[i])
}
@
\end{document}
產生
如何使用 TeX 排版 R 迴圈輸出的值?換句話說,如何\loop...\repeat
使用 TeX over R 迴圈變數。
答案1
您可以使用擴充表包裹:
<<loop-data, results='asis'>>=
library(xtable)
for (i in 1:nrow(df)) {
print(xtable(t(df[i])))
}
@
或使用該kable()
函數針織物:
<<loop-data, results='asis'>>=
for (i in 1:nrow(df)) {
kable(t(df[i]), row.names=FALSE)
}
@
關鍵是 chunk 選項results='asis'
。