Steve G. Jones
Steve G. Jones

Reputation: 335

Continue with the output from a previous chunk in rmarkdown

I would like to use/continue with the output from a previous chunk in rmarkdown as follows:

```{r one}
x <- 1
print(x)
```

```{r two}
x <- x + 10
print(x)
```

```{r three, use.output.from = "one"}
x <- x * 2
print(x)
```

Here, the last chunk should work with x as created in the chunk with label "one". In other words, chunk "three" should print "2" instead of "22".

I have tried to set

```{r three, dependson = "one"}
print(x)
```

which doesn't work as it prints "22" instead of "2". Also

```{r three,ref.label = "one"}
x <- x * 2
print(x)
```

does not work and prints "1" instead of "2" (and it performs the entire chunk "one" again in full).

Is there a chunk option that allows me to call x as outputted from "one" rather than from "two" in chunk "three"? Perhaps by caching x in "one" and then calling that specific cache? Or there may be another approach. Ideally, it would work something like "exercise.setup" in learnr (I don't know how that works, but it doesn't appear to execute "one" again).

Upvotes: 0

Views: 514

Answers (1)

asafpr
asafpr

Reputation: 357

You can use local to declare a new local scope so the global variables will not be changed.

```{r one}
x <- 1
print(x)
```

```{r two}
local({
x <- x + 10
print(x)
})
```

```{r three, use.output.from = "one"}
x <- x * 2
print(x)
```

Upvotes: 1

Related Questions