JdeMello
JdeMello

Reputation: 1718

Hiding part of R code in Rmarkdown

How do I omit parts of a chunk in Rmarkdown?

For instance:

```{r echo T, eval = T}
df <- readRDS("yourfile.RDS")
df <- readRDS("secretfile.RDS") ### NEED TO OMIT THIS PART ONLY
df
```

I am aware of the include = F, or echo = F options but that would either omit the output of df or omit the code entirely.

Alternatively, I could do:

```{r echo T, eval = F}
df <- readRDS("yourfile.RDS")
```
```{r echo = F, eval = T}
df <- readRDS("secretfile.RDS") ### NEED TO OMIT THIS PART ONLY
```
```{r eval = T, echo = T}
df
```

But that is a clunky way to do it and it chops the code blocks. The output should look like:

df <- readRDS("yourfile.RDS")
df

With the output of df following.

Thanks!

Edit: "yourfile.RDS" is a placeholder for demonstration purposes in my document. Therefore, the line of code df <- readRDS("yourfile.RDS") cannot be evaluated.

Upvotes: 0

Views: 3341

Answers (2)

be_green
be_green

Reputation: 753

You can hide the code, but put it above the unevaluated code block. Then after the unevaluated code block (that is displayed), you can create another evaluated but hidden code block that returns your df.

For example:

```{r echo = F, eval = T}
df <- readRDS("secretfile.RDS") ### NEED TO OMIT THIS PART ONLY
```
```{r echo = T, eval = F}
df <- readRDS("yourfile.RDS")
df
```
```{r echo = F, eval = T}
df
```

OP here. Thanks @be_green! Just a slight improvement to your code above:

```{r echo = T, eval = F}
df <- readRDS("yourfile.RDS")
df
```
```{r echo = F, eval = T}
df <- readRDS("secretfile.RDS") ### NEED TO OMIT THIS PART ONLY
df
```

Upvotes: 1

user2554330
user2554330

Reputation: 44788

The echo parameter can take numbers, not just TRUE or FALSE. They are treated as indices into the vector of expressions in the chunk.

So to hide the second line of code, use echo = -2.

The eval parameter also accepts indices, but it will display things with comment markers if you set them not to be eval'd, so you can't (easily?) display line 1 but execute line 2. You can do this:

```{r eval=-1, echo=-2}
a <- 1
b <- 2
c <- 3
```

and line 1 won't be executed. The chunk will be displayed as

## a <- 1
c <- 3

Upvotes: 8

Related Questions