【问题标题】:RMarkdown Inline Code FormatRMarkdown 内联代码格式
【发布时间】:2017-02-12 01:10:35
【问题描述】:

我目前正在阅读ISL,这与 R 中的机器学习有关

我真的很喜欢这本书的具体布局,作者引用了内联代码或库,例如library(MASS)

有谁知道是否可以使用 R Markdown 实现相同的效果,即当我在论文中引用 MASS 关键字时,将其设为棕色以上?当我在 R Markdown 文档中谈论它们时,我想对数据框中的列进行颜色编码。当您将它编织为 HTML 文档时,它提供了非常好的格式,但是当我将它编织到 MS Word 时,它似乎只是更改了字体类型

谢谢

【问题讨论】:

  • 我不太了解您的具体问题,但我认为答案可能是:不要使用 MS Word。请改用 HTML 或 LaTeX 输出。
  • 您好康拉德...非常感谢您的快速回复。本质上,如果您在原始帖子的 ISL 链接中打开 PDF,则书中的介绍会通过一个数据集,并且当他们在书中谈论它时,每一列都会突出显示为棕色。我想达到同样的效果。我正在使用 MS Word,因为它允许我的主管和合作者在边缘使用 cmets
  • 我不确定是否可以在 Word 中完成,但请查看 stackoverflow.com/questions/16405536/…stackoverflow.com/questions/16184962/…

标签: r r-markdown


【解决方案1】:

我想出了一个我认为可以解决您的问题的解决方案。本质上,因为内联源代码与代码块具有相同的样式标签,所以您对 SourceCode 所做的任何更改都将应用于这两个块,我认为这不是您想要的。相反,需要有一种方法只针对内联代码,这在rmarkdown 中似乎是不可能的。相反,我选择做的是获取生成的 .docx 文件,将其转换为 .zip 文件,然后修改其中包含所有数据的 .xml 文件。它将新样式应用于内联源代码文本,然后可以在您的 MS Word 模板中进行修改。代码如下:

format_inline_code = function(fpath) {
  if (!tools::file_ext(fpath) == "docx") stop("File must be a .docx file...")
  cur_dir = getwd()
  .dir = dirname(fpath)
  setwd(.dir)
  out = gsub("docx$", "zip", fpath)

  # Convert to zip file
  file.rename(fpath, out)

  # Extract files
  unzip(out, exdir=".")

  # Read in document.xml
  xml = readr::read_lines("word/document.xml")

  # Replace styling
  # VerbatimChar didn't appear to the style that was applied in Word, nor was
  # it present to be styled. VerbatimStringTok was though.
  xml = sapply(xml, function(line) gsub("VerbatimChar", "VerbatimStringTok", line))

  # Save document.xml
  readr::write_lines(xml, "word/document.xml")

  # Zip files
  .files = c("_rels", "docProps", "word", "[Content_Types].xml")
  zip(zipfile=out, files=.files)

  # Convert to docx
  file.rename(out, fpath)

  # Remove the folders extracted from zip
  sapply(.files, unlink, recursive=TRUE)

  setwd(cur_dir)
}

您要在 MS Word 模板中修改的样式是 VerbatimStringTok。希望对您有所帮助!

【讨论】:

    猜你喜欢
    • 2023-02-01
    • 1970-01-01
    • 2017-12-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-20
    • 1970-01-01
    • 2018-11-20
    相关资源
    最近更新 更多