10.5 Weave R code into Markdown using knitr - Video Tutorials & Practice Problems
Video duration:
2m
Play a video:
<v Voiceover>Now that</v> we've seen the basics of Markdown, let's put in some R code to see how it works. So let's get rid of his image text right here because we're gonna make a new image using R. We're just gonna do something simple to demonstrate something very, very, very simple. So a chunk using Markdown is a little different than a chunk using LaTeX. The way you start a chunk is three back ticks, that's the same key as the tilde, open curly brace, lowercase r. Then you put the name of the chunk, we'll say addition, and then you can close it with a closing curly brace. Right in here, we can do something such as 1 + 1. Then we close the chunk by doing three back ticks. Now let's look at something a little more complicated that will give us some more results. So we do another chunk, then we say more complex, and in here we will go ahead and require ggplot2 and data diamonds and head of diamonds. Let's just run this and see what we get. Ctrl + Shift + H runs it or clicking the Markdown button. And here we go, we have an R command and then the result. An R command, result, more R commands, more results. This is great for posting to a website by the way so if you want to see a tutorial on R or you can get really complex, you can make reports that generate automatically for your office. Integrating graphics is just as simple as integrating code. So we'll do three back ticks, curly brace r, we'll say a simple plot. Then we will go maybe ggplot diamonds, aes x=carat, y=price, color=color + geom_point. Remember to close the chunk and it's a good idea here to specify the dev, which is dev and I like png. If we run this, again, running with Ctrl + Shift + H, it draws the image, makes file and puts it right into the website. Couldn't get much easier writing websites using R. And this is highly extensible. This can be used, like I said, a blog post or if you were to run daily reports like at 6am everyday, you could have it all automated with R and generate a website with all images and graphics you need. This has been further extended by this Professor at McGill University named Ramnath Vaidyanathan and he has a thing called R charts which let you build interactive R charts using knitr and Markdown. Knitr puts the data into D3 and makes these beautiful, interactive graphics all from within the comfort of R, all from the ease of R code. Makes life really great, all thanks to knitr and Markdown.