uncool
uncool

Reputation: 2693

Possible to pass argument to code_chunk in knitr?

I'm very new to knitr and especially the ability to read_chunk. I've been looking into if there is a possibility to pass arguments to a code chunk, but haven't found/understood the right resource yet. Is this possible and if so how?

My external R script code looks like this

  ## @knitr plotX

  plot.1  <- ggplot(df, aes(x = year, y = values, colour = names)) + 

    geom_line(aes(group = names)) + 
    scale_y_continuous(labels = scales::comma) + 
    scale_colour_brewer(palette = "Paired") +
    ylab("Expenses in SEK") +
    labs(colour = "Household Group") +
    theme_classic()

  plot.list  <- list("per housegroup" = plot.1, df)

  return(plot.list)
  ## -----

In my .Rmd file, can I somehow pass the df argument within an argument?

Such as

```{r} 
knitr::read_chunk('document.R')
<<plotX, argument df = object x>> 
```

Upvotes: 2

Views: 958

Answers (1)

bergant
bergant

Reputation: 7232

If your code in document.R is using a variable named df then just set it before the chunk where you are using external code. For example:

document.R

# ---- my-chunk ----
plot(df)

test.Rmd

```{r cache=FALSE}
# this reads the code (but does not evaluate yet):
knitr::read_chunk('document.R') 
```

```{r}
# assign df
df <- iris
```

```{r my-chunk}
```

Note that the last chunk name matches the code section label in document.r

See also http://yihui.name/knitr/demo/externalization/

Update

As @user2706569 commented: a cleaner approach would be to wrap the plotting code in a function and just source the document.R file.

Upvotes: 4

Related Questions