Access name of .rmd file and use in R

自闭症网瘾萝莉.ら 提交于 2021-01-27 06:21:09

问题


I am knitting a markdown file called MyFile.rmd. How can I access the string MyFile during the knitting and use it for:

  • use in the title section of the YAML header?
  • use in subsequent R chunk?

    ---
    title: "`r rmarkdown::metadata$title`"
    author: "My Name"
    date: "10. Mai 2015"
    output: beamer_presentation
    ---
    
    ## Slide 1
    
    ```{r}
    
    rmarkdown::metadata$title
    
    ```
    

leads to...

enter image description here

... which is incorrect as the file I am knitting is named differently.

> sessionInfo()
R version 3.1.2 (2014-10-31)
Platform: x86_64-apple-darwin13.4.0 (64-bit)

locale:
[1] de_DE.UTF-8/de_DE.UTF-8/de_DE.UTF-8/C/de_DE.UTF-8/de_DE.UTF-8

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

loaded via a namespace (and not attached):
[1] digest_0.6.8    htmltools_0.2.6 rmarkdown_0.5.1 tools_3.1.2     yaml_2.1.13

回答1:


rmarkdown::metadata gives you the list of the meta data of the R Markdown, e.g. rmarkdown::metadata$title will be the title of your document. An example:

---
title: "Beamer Presentation Title"
author: "My Name"
date: "10\. Mai 2015"
output: beamer_presentation
---

## Slide 1

Print the title in a code chunk.

```{r}
rmarkdown::metadata$title
```

## Slide 2

The title of the document is `r rmarkdown::metadata$title`.

To obtain the filename of the input document, use knitr::current_input().




回答2:


You could use the yaml library, like so:

library(yaml)

# Read in the lines of your file
lines <- readLines("MyFile.rmd")
# Find the header portion contained between the --- lines. 
header_line_nums <- which(lines == "---") + c(1, -1)
# Create a string of just that header portion
header <- paste(lines[seq(header_line_nums[1], 
                          header_line_nums[2])], 
                collapse = "\n")
# parse it as yaml, which returns a list of property values
yaml.load(header)

If you save the list returned by yaml.load, you can use it in various chunks as needed. To get the title, you can do this:

properties <- yaml.load(header)
properties$title



回答3:


Just summarize Yihui's answer:

    ---
    title: "`r knitr::current_input()`"
    author: "My Name"
    date: "10. Mai 2015"
    output: beamer_presentation
    ---

    ## Slide 1

    ```{r}

    knitr::current_input()

    ```

which knitted does the job.

enter image description here



来源:https://stackoverflow.com/questions/30153194/access-name-of-rmd-file-and-use-in-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!