将sjPlot::tab_model()或其他html表格的输出编织成PDF文档。

问题描述 投票:0回答:1

正如标题所描述的那样,我正试图找到一种方法来编织来自于 sjPlot::tab_model() 和其他HTML表格到一个由LaTeX生成的PDF文档中,使用的是 knitr.

因此,我正在寻找一个替代功能来替代 tab_model() 生成一个数据框架或LaTeX表作为输出,而不是HTML。或者,一个将html表格转换为LaTeX代码的函数,或者一个数据框架,而我又可以用它来转换为LaTeX表格。knitr::kable()papaja::apa_table().

例子。

\documentclass{apa7}

\begin{document}

Either a an alternative function that provides LaTeX output:

<<echo=FALSE>>=
model <- lm(carb ~ mpg, mtcars) #Linear model on mtcars dataset
desc <- "alternative2tab_model"(model) # Creates LaTeX table of descriptives
@


Or a function that directly converts HTML to LaTeX:

<<echo=FALSE>>=
model <- lm(carb ~ mpg, mtcars) #Linear model on mtcars dataset
desc <- sjPlot::tab_model(model) # Creates HTML table of descriptives

"html2latex"(desc) # Some function that will convert HTML to LaTeX
@

Or a function that converts HTML to dataframe:

<<echo=FALSE>>=
model <- lm(carb ~ mpg, mtcars) # Linear model on mtcars dataset
desc <- sjPlot::tab_model(model) # Creates HTML table of descriptives

desc_df <- "html2dataframe"(desc) # Some function that will convert HTML to data frame:

papaja::apa_table(desc_df, format = "latex") # Convert data frame into APA-style LaTeX table:
@

\end{document}
r latex knitr sjplot
1个回答
0
投票

好吧,我找到了一个解决方案,使用了以下方法 XML::readHTMLtable(). 然而,它需要一些争论,因为 readHTMLtable() 不接受 tab_model()的输出。基本上,我必须从 tab_model 包含HTML代码,并将它们添加到一个字符向量中,该向量可以在 readHTMLtable. readHTMLtable 创建了一个包含两个迭代数据帧的列表,因此在运行之前必须先删除一个数据帧。apa_table.

\documentclass{apa7}
\begin{document}
<<echo=FALSE, cache=TRUE>>=
m1 <- lm(carb ~ mpg, mtcars)
m1list <- tab_model(m1)
# Creating vector containing HTML code
m1vec <- c() 
for (i in 1:3) {
  m1vec[i] <- m1list[[i]]
}
# Reading into data frame.
m1df <- XML::readHTMLTable(m1vec, as.data.frame = TRUE)
# Data frame is retrieved as repeated items in list. Keeping only one.
m1df <- m1df[[1]]
# Setting column names correctly.
colnames(m1df) <- m1df[1,]
m1df <- m1df[-1,]
# Converting data frame into LaTeX code.
papaja::apa_table(m1df)
@
\end{document}

这个解决方案可能只适用于这个例子。这将需要一些时间来计算如何创建一个通用函数。欢迎添加任何改进建议。

© www.soinside.com 2019 - 2024. All rights reserved.