Open mtwelker opened 3 years ago
Great question, @mtwelker!
This is called inline code (read more). When should you use it versus putting your code in a code chunk?
Really, inline code snippets are most useful and most used (extremely valuable, in fact) when you are creating a reproducible report that is data agnostic. When new data emerge and are fed into your R Markdown report, you can make the human-readable portions dynamic and change in response to new data.
If I want to write up some human-readable text in an R Markdown report, what happens if I want to include some average or median or other helpful summary value? Well, by using inline values, you can make the text update dynamically. What's tat look like? Well, take this Markdown code:
This week, I walked an average of `r x` steps.
Here, we can take object x
and assign it any value we want, and the text will come out as:
This week, I walked an average of 84000 steps.
You could even format it in the inline code snippet using something like the scales
package:
This week, I walked an average of `r comma(x)` steps.
This formats to:
This week, I walked an average of 84,000 steps.
When should we use code chunks, instead? Well, if you are writing all of your code inline, it's going to look like a hot mess! Think of code chunks as organized areas to share your code with your audience, or simply to organize your code for yourself, and you can choose to show or conceal your code in your report.
Typically, you would use these (inline code and code chunks) together and in conjunction. You could perform the actual processing/heavy lifting in a code chunk to determine, e.g., a value for x
. Then, inline, you could insert that value into your report - and it would be virtually indistinguishable from the rest of the text.
As a fun example, here's an admissions report I created for Georgia State University (with dummy data). Just about all text in boldface is actually an inline value. You can see this in the .gifs in the very beginning - explained in "About This Sample: Dynamic Reporting": https://rpubs.com/jamisoncrawford/admissions
If you look at the code underneath the report, you'll see the code chunks and inline in all their glory.
Hope this helps!
Very helpful. Thank you!
In our assignments, when I type in the answer manually, I always worry about typos. So I learned that I can embed R code in a line of markdown as follows:
(Please correct me if I'm not using the right terms here.)
Is there any reason that I shouldn't do that? Is it considered bad form or bad style to do the calculation within a line of regular text, rather than within the code block? It doesn't display the answer separately on the knitted document and the r code within the line does not display on the knitted document, so is that a problem for you as a professor (@lecy @jamisoncrawford) when you're looking over our assignments? Thank you!