Module 01 Lesson 1: R Markdown Nik Bear Brown July 28, 2015 Lesson 1: R Markdown In the frst lesson, we start the module discussing R arkdown to create written re!orts with em"edded working code# R arkdown is an authoring $ormat that ena"les easy creation o$ dynamic documents, !resentations, and re!orts $rom R# It com"ines the core synta% o$ markdown &an easy'to'write !lain te%t $ormat( with em"edded R code chunks that are run so their out!ut can "e included in the fnal document# R arkdown documents can "e regenerated whene)er underlying R code or data changes# *his is an R arkdown document# arkdown is a sim!le $or matting synta% $or authoring +*, -./, and or d documents# /or more details on using R arkdown see htt!33rmarkdown#rstudio#com # In odule 01 esson 1 we will learn a"out R arkdown synta%# *he $ollowing lessons and assingments all will use R arkdown# R arkdown is an authoring $ormat that ena"les easy creation o$ dynamic documents, !resentations, and re!orts $rom R# It com"ines the core synta% o$ markdown &an easy'to'write !lain te%t $ormat( with em"edded R code chunks that are run so their out!ut can "e included in the fnal document# R arkdown documents are $ully re!roduci"le &they can "e automatically regenerated whene)er underlying R code or data changes(# *he Rarkdown we"site & htt!33rmarkdown#rstudio#com3 ( descri"es R arkdown )2, a ne%t generation im!lementation o$ R arkdown "ased on knitr and !andoc# *his im!lementation "rings many enhancements to R arkdown, includingany a)aila"le out!ut $ormats including +*, -./, and ord# u!!ort $or creating Beamer, ioslides, and lidy !resentations# New markdown synta% including e%!anded su!!ort $or ta"les and "i"liogra!hies# 4 +ooks $ or cust omi in g +* a nd - ./ o ut!ut & inc lude 6, headers, and $ooters(# 4 Include raw a* e7 withi n mar kdown $or ad)anced customi ation o $ -./ out!ut#
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
In the frst lesson, we start the module discussing R arkdown tocreate written re!orts with em"edded working code# R arkdown is anauthoring $ormat that ena"les easy creation o$ dynamic documents,!resentations, and re!orts $rom R# It com"ines the core synta% o$markdown &an easy'to'write !lain te%t $ormat( with em"edded R codechunks that are run so their out!ut can "e included in the fnaldocument# R arkdown documents can "e regenerated whene)erunderlying R code or data changes#
*his is an R arkdown document# arkdown is a sim!le $ormattingsynta% $or authoring +*, -./, and ord documents# /or moredetails on using R arkdown see htt!33rmarkdown#rstudio#com#
In odule 01 esson 1 we will learn a"out R arkdown synta%# *he$ollowing lessons and assingments all will use R arkdown#
R arkdown is an authoring $ormat that ena"les easy creation o$dynamic documents, !resentations, and re!orts $rom R# It com"inesthe core synta% o$ markdown &an easy'to'write !lain te%t $ormat( withem"edded R code chunks that are run so their out!ut can "e includedin the fnal document# R arkdown documents are $ully re!roduci"le&they can "e automatically regenerated whene)er underlying R code ordata changes(#
*he Rarkdown we"site &htt!33rmarkdown#rstudio#com3( descri"es Rarkdown )2, a ne%t generation im!lementation o$ R arkdown "asedon knitr and !andoc# *his im!lementation "rings many enhancementsto R arkdown, including
any a)aila"le out!ut $ormats including +*, -./, and ord#
u!!ort $or creating Beamer, ioslides, and lidy !resentations# Newmarkdown synta% including e%!anded su!!ort $or ta"les and"i"liogra!hies#
FF Mdata#$rameM 5DG0 o"s# o$ 10 )aria"lesFF carat num 0#2D 0#21 0#2D 0#2 0#D1 0#2G 0#2G 0#2 0#22 0#2D ###FF cut ?rd#$actor w3 5 le)els >/air>O>Aood>O## 5 G 2 G 2 D D D 1 D ###FF color ?rd#$actor w3 K le)els >.>O>>O>/>O>A>O## 2 2 2 K K 5 25 ###FF clarity ?rd#$actor w3 8 le)els >I1>O>I2>O>I1>O## 2 D 5 G 2 K D G 5 ###
Note that the echo P / !arameter was added to the code chunk to!re)ent !rinting o$ the R code that generated the !lot#
/or e%am!le, the $ollowing code
Inline R Code
Eou can also e)aluate R e%!ressions inline "y enclosing the e%!ressionwithin a single "ack'tick 9ualifed with MrM# /or e%am!le, the $ollowingcode
arkdown Inline
Results in this out!ut >I counted 2 red trucks on the highway#>
-nitting
hen you click the -nit "utton a document will "e generated thatincludes "oth content as well as the out!ut o$ any em"edded R codechunks within the document#
*o insert an R code chunk, you can ty!e it manually or =ust !ress6hunks ' Insert chunks or use the shortcut key# *his will !roduce the$ollowing code chunk
-ressing ta" when inside the "races will "ring u! code chunk o!tions#
*he $ollowing R code chunk la"elled "asicconsole is as $ollows
UUUr% O' 110y O' round&rnorm&10, %, 1(, 2(d$ O' data#$rame&%, y(
d$ UUU
UUUFF % yFF 1 1 0#2FF 2 2 D#DFF D D 0#5FF G G G#28FF 5 5 D#GKFF 5#KDFF K K 8#2D
FF 8 8 8#DFF #D5FF 10 10 #GGUUU
*he code chunk in!ut and out!ut is then dis!layed as $ollows
% O' 110 y O' round&rnorm&10, %, 1(, 2( d$ O' data(/rame&%, y( d$
FF % yFF 1 1 '0#12FF 2 2 1#1DFF D D D#0GFF G G D#G2FF 5 5 G#18FF #11FF K K K#DFF 8 8 8#05
Images generated "y knitr are sa)ed in a fgures $older# +owe)er, theyalso a!!ear to "e re!resented in the +* out!ut using a data TRIscheme# *his means that you can !aste the +* into a "log !ost or
discussion $orum and you donMt ha)e to worry a"out fnding a !lace tostore the imagesC theyMre em"edded in the +*#
% \ y ''' \ ''' 1 \ '0#12 2 \ 1#1D D \ D#0G G \ D#G2 5 \ G#18 \ #11 K \ K#D8 \ 8#05 \ 10#DK 10 \ #2
Control output displa)
*he $olllowing code su!resses dis!lay o$ R in!ut commands &i#e#,echoP/( and remo)es any !receding te%t $rom console out!ut&commentP>>C the de$ault is commentP>FF>(#
UUU
% y1 1 '0#122 2 1#1DD D D#0GG G D#G25 5 G#18 #11UUU
% y1 1 '0#122 2 1#1D
D D D#0GG G D#G25 5 G#18 #11
Cache anal)sis
6aching analyses is straight$orward# +ereMs e%am!le code# ?n the frstrun on my com!uter, this took a"out 10 seconds# ?n su"se9uent runs,this code was not run#
I$ you want to rerun cached code chunks, =ust delete the contents o$
the cache $olderUUUr$or &i in 15000( Q lm&&i[1(Yi(SUUU
&same as a*e7( dou"le "ackslash Z&inlineZ( and Z:dis!layZ; naked late%en)ironment
#
9uations are included "y using a*e7 notation and including them
either "etween single dollar signs &inline e9uations( or dou"le dollarsigns &dis!layed e9uations(# I$ you hang around the H] site6rossLalidated youMll "e $amiliar with this idea#
*here are inline e9uations such as y i=α + β x i+e i #
nd dis!layed $ormulas
1
1+exp (− x)
)pesetting uations
Inline !s( %ispla) Material
9uations can "e $ormatted inline or as displayed formulas# In thelatter case, they are centered and set o^ $rom the main te%t# In the$ormer case, the mathematical material occurs smoothly in the line o$te%t#
In order to ft neatly in a line, summation e%!ressions &and similar
constructs( are $ormatted slightly di^erently in their inline and dis!lay)ersions#
Inline mathematical material is set o^ "y the use o$ single dollar'signcharacters# 6onse9uently, i$ you wish to use a dollar sign &$or e%am!le,to indicate currency(, you need to !re$ace it with a "ack'slash# *he$ollowing e%am!les, $ollowed "y their ty!eset )ersions, should makethis clear
In this section, we show you some rudiments o$ the a*e7 ty!esettinglanguage#
Su'scripts and Superscripts
*o indicate a su"scri!t, use the underscore character# *o indicate asu!erscri!t, use a single caret character X# Note this can "e con$using,"ecause the R arkdown language delimits su!erscri!ts with twocarets# In a*e7 e9uations, a single caret indicates the su!erscri!t#
I$ the su"scri!t or su!erscri!t has =ust one character, there is no needto delimit with "races# +owe)er, i$ there is more than one character,
"races must "e used#
*he $ollowing e%am!les illustrate
7i7QiS
X i
X i
Notice that in the a"o)e case, "races were not actually needed#In this ne%t e%am!le, howe)er, $ailure to use "races creates an error,as a*e7 sets only the frst character as a su"scri!t
+ere is an e%!ression that uses "oth su"scri!ts and su!erscri!ts7X2Qi,=S
X i , j2
Suare Roots
e indicate a s9uare root using the Zs9rt o!erator#
Zs9rtQ"X2 ' GacS
√ b2
−4
ac
ractions
.is!layed $ractions are ty!eset using the Z$rac o!erator#
Z$racQGXDSQ1S
4 z3
16
Summation 3pressions *hese are indicated with the UM o!erator, $ollowed "y a su"scri!t $or thematerial a!!earing "elow the summation sign, and a su!erscri!t $orany material a!!earing a"o)e the summation sign#
+ere is an e%am!le#
ZsumQiP1SXQnS 7XDi
∑i=1
n
X i3
Sel/;Si9ing $arentheses
In a*e7, you can create !arentheses, "rackets, and "races which siethemsel)es automatically to contain large e%!ressions# Eou do thisusing the Zle$t and Zright o!erators# +ere is an e%am!le
any statistical e%!ressions use Areek letters# uch o$ the Areekal!ha"et is im!lemented in a*e7, as indicated in the a*e7 cheatsheet a)aila"le at the course we"site# *here are "oth u!!er and lowercase )ersions a)aila"le $or some letters#
Zal!ha, Z"eta, Zgamma, ZAamma
α , β , γ , Γ
Special S)m'ols
ll common mathematical sym"ols are im!lemented, and you can fnda listing on a a*e7 cheat sheet#
V u"scri!ts to get Z& aQ"S Z( write aQ"SV u!erscri!ts write Z& aXQ"S Z( write aXQ"SV Areek letters like Z& Zal!ha, Z"eta, Zldots Z( write Zal!ha, Z"eta, ZldotsV ums like Z& ZsumQnP1SXN Z( write ZsumQnP1SXNV ulti!lication like Z& Ztimes Z( write ZtimesV -roducts like Z& Z!rodQnP1SXN Z( write Z!rodQnP1SXNV Ine9ualities like Z& O, Zle9, Zge9 Z( write O, Zle9, Zge9V .istri"uted like Z& Zsim Z( write ZsimV +ats like Z& ZwidehatQZal!haS Z( write ZwidehatQZal!haS
V )erages like Z& Z"arQ%S Z( write Z"arQ%SV /ractions like Z& Z$racQaSQ"S Z( write Z$racQaSQ"S
ome e%am!les# &Notice that, in the third e%am!le, I use the tildecharacter $or a $orced s!ace# Aenerally a*e7 does s!acing $or youautomatically, and unless you use the tilde character, R will ignoreyour attem!ts to add s!aces#(
a Z!m "% Zge 15ai Zge 0YYYZ$orall i
a ± b
x ≥ 15
ai ≥ 0∀ i
Special unctions
a*e7 ty!esets s!ecial $unctions in a di^erent $ont $rom mathematical
)aria"les# *hese $unctions, such assin
,cos
, etc# are indicated ina*e7 with a "ackslash# +ere is an e%am!le that also illustrates how toty!eset an integral#
Zint0XQ2Z!iS Zsin %Yd%
∫0
2π
sin x dx
Matrices
atrics are !resented in the array en)ironment# ?ne "egins with thestatement Z"eginQarrayS and ends with the statement ZendQarrayS#/ollowing the o!ening statement, a $ormat code is used to indicate the$ormatting o$ each column# In the e%am!le "elow, we use the codeQrrrS to indicate that each column is right =ustifed# ach row is thenentered, with cells se!arated "y the ] sym"ol, and each line &e%ce!tthe last( terminated "y ZZ#
In math te%t"ooks, matrices are o$ten surrounded "y "rackets, and areassigned to a "old$ace letter# +ere is an e%am!le
Zmath"$Q7S P Zle$t:Z"eginQarraySQrrrS
1 ] 2 ] D ZZG ] 5 ] ZZK ] 8 ] ZendQarraySZright;
X =[1 2 3
4 5 6
7 8 9]
Math=a3 script
knitr !ro)ides sel$'contained +* code that calls a ath=a% scri!t todis!lay $ormulas# +owe)er, in order to include the scri!t in my "log!osts I took the scri!t and incor!orated it into my "logger tem!late# I$you are )iewing this !ost through syndication or an R reader, thismay not work# Eou may need to )iew this !ost on my we"site#
a'les
*a"les can "e included using the $ollowing notation
\ B \ 6 ''' \ ''' \ ''' 1 \ ale \ Blue 2 \ /emale \ -ink
4)perlinks4 +ere is my "log nik"ear"rown#com my "log nik"ear"rown#com#