简体   繁体   中英

How can I refer to an R code (chunk) on a different page using R markdown (reproducible example provided in the text)

Let's say I have an R markdown pdf document that have 2 pages.

# page 1
R code that was used to perform the regression analysis can be found by clicking HERE.

What I want is when I click on "HERE" it refers/takes me to the code in the page two. Suppose the page 2 contains the following code.

# page 2
model = lm(y~x, data = data)

Any ideas?

You have to link the anchor to a heading, as far as I know. One workaround to link to a plot would be to add an empty heading below it.

Create an anchor next to an empty heading below the plot, like this:

# {#YourAnchorNextToTheHeading} .

Wrap the word/sentence you want the link into in square brackets [] , followed by your anchor wrapped around round brackets.

Here is an example:

# page 1
R code that was used to perform the regression analysis can be found by clicking [HERE](#page2).



\pagebreak

# page 2

```{r echo = FALSE}
plot(cars)

```

# {#page2}

EDIT: Adding color to the linked text:

I found this on the the R Cookbook tutorial: :

Create a R function to write raw HTML or LaTeX code:

```{r echo=FALSE, include=FALSE}
colorize <- function(x, color) {
  if (knitr::is_latex_output()) {
    sprintf("\\textcolor{%s}{%s}", color, x)
  } else if (knitr::is_html_output()) {
    sprintf("<span style='color: %s;'>%s</span>", color, 
      x)
  } else x
}

```

Then add it to the text ( make sure to wrap r colorize("HERE", "blue") with back ticks (`) )

page 1

R code that was used to perform the regression analysis can be found by clicking r colorize("HERE", "blue") .

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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