有人问如何将输出转换为pdf,这里提供一个使用knitr的答案,并且使用比\includegraphics更合适的方法。
![Table with flags](https://istack.dev59.com/O6DKJ.webp)
关键是在latex中使用adjustbox包,以下是参数:
- height(稍后用作R函数get_picture_code的参数)是图片的高度。
- valign参数(此处默认为valign=m)将根据文本执行垂直调整,
- margin在此处定义为1ex,围绕图片分隔旗帜。
因此,我们只需使用此功能即可
get_picture_code <- function(path,height,col=NULL)
{
paste0("\\adjustimage{height=",height,",valign=m,margin*=1ex}{",path,"}")
}
获取添加到表格中的图像向量。
最后,我们使用参数
sanitize.text.function = identity
的xtable来打印TeX代码:
\documentclass{article}
\usepackage{adjustbox}
\begin{document}
<<load_libraries, echo = FALSE, eval = TRUE, results ="hide">>=
library(knitr)
library(xtable)
@
<<include_images, echo = FALSE, eval = TRUE, results ="hide">>=
get_picture_code <- function(path,height,col=NULL){
paste0("\\adjustimage{height=",height,",valign=m,margin*=1ex}{",path,"}")
}
@
<<test, echo = FALSE, eval = TRUE, results ="hide">>=
dat <- data.frame(country = c("Belgium", "Germany", "Holland", "Ireland"),
Var1 = 1:4, Var2 = 11:14)
mypath <- paste0("images/",dat$country,".png")
dat$flag <- get_picture_code(path=mypath,height="0.8cm")
dat$test <-NA
dat$test[2:3] <-get_picture_code(path="images/orange_flag",height="0.6cm")
print(xtable(dat,
align = c("l","l","l","l","c","c"),
caption = "Example with flags"),
sanitize.text.function = identity,
file="table_with_images.tex")
@
\input{table_with_images.tex}
\end{document}
adjustbox文档包含许多其他选项,包括背景颜色、修剪、水平对齐等,这将使您能够对图像的位置进行精细调整...
此外,在TeX-Latex stackexchange中还有一个很好的使用示例。