简体   繁体   English

使用knitr / kable在LaTeX表中链接文本

[英]Linked text in LaTeX table with knitr/kable

I have the following dataframe: 我有以下数据帧:

site_name           | site_url
--------------------| ------------------------------------
3D Printing         | https://3dprinting.stackexchange.com
Academia            | https://academia.stackexchange.com
Amateur Radio       | https://ham.stackexchange.com

I want to generate a third column with the link integrated with the text. 我想生成第三列,其中链接与文本集成。 In HTML I came up with the following pseudo code: 在HTML中我想出了以下伪代码:

df$url_name <- "[content of site_name](content of site_url)"

resulting in the following working program code: 产生以下工作程序代码:

if (knitr::is_html_output()) {
    df <- df %>% dplyr::mutate(url_name = paste0("[", df[[1]], "](", df[[2]], ")"))
    knitr::kable(df)
}

Is there a way to this in LaTeX with knitr as well? 有没有一种方法可以在LaTeX中使用knitr

(I am preferring a solution compatible with kableExtra , but if this is not possible I am ready to learn whatever table package can do this.) (我更喜欢与kableExtra兼容的解决方案,但如果这不可能,我准备学习任何表包可以做到这一点。)

*** ADDED: I just noticed that the above code works within a normal .Rmd document with the yaml header output: pdf_document . ***添加:我刚刚注意到上面的代码在带有yaml标头output: pdf_document的普通.Rmd文档中工作output: pdf_document But not in my bookdown project. 但不是在我的bookdown项目中。

The problem is with knitr::kable . 问题出在knitr::kable It doesn't recognize that the bookdown project needs Markdown output, so you need to tell it that explicitly: 它无法识别bookdown项目需要Markdown输出,因此您需要明确告诉它:

df <- df %>% dplyr::mutate(url_name = paste0("[", df[[1]], "](", df[[2]], ")"))
knitr::kable(df, format = "markdown")

This will work for any kind of Markdown output: html_document , pdf_document , bookdown::pdf_book , etc. 这适用于任何类型的Markdown输出: html_documentpdf_documentbookdown::pdf_book等。

Alternatively, if you need LaTeX output for some other part of the table, you could write the LaTeX equivalent. 或者,如果您需要LaTeX输出用于表的其他部分,则可以编写LaTeX等效项。 This won't work for HTML output, of course, but should be okay for the PDF targets: 当然,这不适用于HTML输出,但对于PDF目标应该没问题:

df <- df %>% dplyr::mutate(urlName = paste0("\\href{", df[[2]], "}{", df[[1]], "}"))
knitr::kable(df, format = "latex", escape = FALSE)

For this one I had to change the column name; 对于这个,我不得不改变列名; underscores are special in LaTeX. 下划线在LaTeX中很特别。 You could probably get away without doing that if you left it as format = "markdown" , but then you'd probably be better off using the first solution. 如果你将它保留为format = "markdown" ,你可能会在没有这样做的情况下逃脱,但是你可能最好使用第一个解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM