How do I iteratively generate multiple inline sentences or paragraphs in RStudio knitted Rmd?

83 views
Skip to first unread message

Tony Hirst

unread,
Mar 29, 2015, 3:16:29 PM3/29/15
to kn...@googlegroups.com
Suppose I have a dataframe with a couple of columns ('name' and 'value') and I want to generate an inline sentence that reports on each row.

For example,  pseudo code might look like:

The value associated with `r df['name']` is `r df['value']`.

which is intended to suggest output:

The value associated with item1 is 25.
The value associated with item2 is 43.
...
The value associated with itemN is 12.

How would I do that?

That is, how can I iteratively declare a sentence or paragraph template that contains inline values I want to iterate over? Note the paragraph may also contain "fixed" "global" inline variables as well as ones that are iterated over.

thanks
tony


Jeff Newmiller

unread,
Mar 29, 2015, 3:25:06 PM3/29/15
to Tony Hirst, knitr

See the for loop example [1].

[1] https://github.com/yihui/knitr-examples/blob/master/020-for-loop.Rnw

--
You received this message because you are subscribed to the Google Groups "knitr" group.
To unsubscribe from this group and stop receiving emails from it, send an email to knitr+un...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Tony Hirst

unread,
Mar 29, 2015, 4:00:22 PM3/29/15
to kn...@googlegroups.com
To partly answer my own question, this approach:

```{r results='asis'}
stints['name']=factor(stints$name)
for (name in levels(stints$name)){
  cat(paste0(knit_child('DELME_demo_sentence.Rmd',quiet=TRUE),'\n\n'))
}
```

in part cribbed from http://stackoverflow.com/a/21046060/454773 goes quite a long way towards what I needed.

The DELME..Rmd file looks like:

`r name` completed `r sum(abs(stints[stints['name']==name,]['l']))` laps over `r nrow(stints[stints['name']==name,])` stints, with a longest run of `r max(abs(stints[stints['name']==name,]['l']))` laps.


The next step is - can I knit_child over something that is included in the same file as the knit_child() element?

Jeff Newmiller

unread,
Mar 29, 2015, 4:07:58 PM3/29/15
to Tony Hirst, knitr

Use the text argument to knit_child.

--

Tony Hirst

unread,
Mar 29, 2015, 4:19:55 PM3/29/15
to kn...@googlegroups.com, tony....@gmail.com

Stéphane Laurent

unread,
Apr 8, 2015, 5:02:22 PM4/8/15
to kn...@googlegroups.com, tony....@gmail.com
Reply all
Reply to author
Forward
0 new messages