Use dataset name in knitr code chunk in R

25 Views Asked by At

How can a dataset name be used in a knitr document?

For example, in the following knitr code chunk, using deparse(substitute(x)) (which normally works in non-knitr R code) does not display New York and Berlin from the cities list in the knitted HTML child documents:

    ```{r plot-data, results='asis'}

    cities <- list(New York, Berlin)

    res <- lapply(cities, function(x) {
      knitr::knit_child(
        text = c(
          '\n',
          '## `r deparse(substitute(x))`',
          '\n',
          '```{r, out.height="100%", out.width="100%"}',
          'some_plotting_function(x)',
          '```'
        ),
        envir = environment(),
        quiet = TRUE
      )
    })

    cat(unlist(res), sep = "\n")
    ```

That is, in the ## comment line, the outputted city names appear as X[[i]] for each one, rather than as New York and Berlin. (I want to use the city names as section titles before calling some_plotting_function() on each one.)

1

There are 1 best solutions below

2
Dark Vedar On BEST ANSWER

To achieve the desired behaviour of correctly displaying city names in the section titles of HTML child documents, you can modify the code to explicitly pass the city names as arguments to the child documents. This is how you can do it:


cities <- list("New York", "Berlin")

res <- lapply(cities, function(city) {
  knitr::knit_child(
    text = c(
      '\n',
      paste0('## ', city),
      '\n',
      '```{r, out.height="100%", out.width="100%"}',
      'some_plotting_function("', city, '")',
      '```'
    ),
    envir = environment(),
    quiet = TRUE
  )
})

cat(unlist(res), sep = "\n")

Here are the changes I made in the above code:

  1. The Cities list has been changed to contain strings instead of objects.
  2. Within the "lapply" loop, "city" is used as the loop variable instead of "x".
  3. The city name is passed as a string argument to "some_plotting_function()" in the child document. This will correctly display city names as section titles in woven HTML sub-documents.