<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title></title>
	<atom:link href="http://sachaepskamp.com/?feed=rss2" rel="self" type="application/rss+xml" />
	<link>http://sachaepskamp.com</link>
	<description></description>
	<lastBuildDate>Wed, 08 May 2013 15:24:26 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.5</generator>
		<item>
		<title>Create HTML page containing all package examples using knitr and markdown</title>
		<link>http://sachaepskamp.com/blog/HTMLexamples</link>
		<comments>http://sachaepskamp.com/blog/HTMLexamples#comments</comments>
		<pubDate>Wed, 23 Jan 2013 15:32:42 +0000</pubDate>
		<dc:creator>sachaepskamp</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[R]]></category>

		<guid isPermaLink="false">http://sachaepskamp.com/?p=515</guid>
		<description><![CDATA[]]></description>
				<content:encoded><![CDATA[

<!DOCTYPE html>
<!-- saved from url=(0014)about:internet -->
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>

<title>Create HTML page containing all package examples using knitr and markdown</title>

<style type="text/css">
body, td {
   font-family: sans-serif;
   background-color: white;
   font-size: 12px;
   margin: 8px;
}

tt, code, pre {
   font-family: 'DejaVu Sans Mono', 'Droid Sans Mono', 'Lucida Console', Consolas, Monaco, monospace;
}

h1 { 
   font-size:2.2em; 
}

h2 { 
   font-size:1.8em; 
}

h3 { 
   font-size:1.4em; 
}

h4 { 
   font-size:1.0em; 
}

h5 { 
   font-size:0.9em; 
}

h6 { 
   font-size:0.8em; 
}

a:visited {
   color: rgb(50%, 0%, 50%);
}

pre {	
   margin-top: 0;
   max-width: 95%;
   border: 1px solid #ccc;
   white-space: pre-wrap;
}

pre code {
   display: block; padding: 0.5em;
}

code.r, code.cpp {
   background-color: #F8F8F8;
}

table, td, th {
  border: none;
}

blockquote {
   color:#666666;
   margin:0;
   padding-left: 1em;
   border-left: 0.5em #EEE solid;
}

hr {
   height: 0px;
   border-bottom: none;
   border-top-width: thin;
   border-top-style: dotted;
   border-top-color: #999999;
}

@media print {
   * { 
      background: transparent !important; 
      color: black !important; 
      filter:none !important; 
      -ms-filter: none !important; 
   }

   body { 
      font-size:12pt; 
      max-width:100%; 
   }
       
   a, a:visited { 
      text-decoration: underline; 
   }

   hr { 
      visibility: hidden;
      page-break-before: always;
   }

   pre, blockquote { 
      padding-right: 1em; 
      page-break-inside: avoid; 
   }

   tr, img { 
      page-break-inside: avoid; 
   }

   img { 
      max-width: 100% !important; 
   }

   @page :left { 
      margin: 15mm 20mm 15mm 10mm; 
   }
     
   @page :right { 
      margin: 15mm 10mm 15mm 20mm; 
   }

   p, h2, h3 { 
      orphans: 3; widows: 3; 
   }

   h2, h3 { 
      page-break-after: avoid; 
   }
}

</style>

<!-- Styles for R syntax highlighter -->
<style type="text/css">
   pre .operator,
   pre .paren {
     color: rgb(104, 118, 135)
   }

   pre .literal {
     color: rgb(88, 72, 246)
   }

   pre .number {
     color: rgb(0, 0, 205);
   }

   pre .comment {
     color: rgb(76, 136, 107);
   }

   pre .keyword {
     color: rgb(0, 0, 255);
   }

   pre .identifier {
     color: rgb(0, 0, 0);
   }

   pre .string {
     color: rgb(3, 106, 7);
   }
</style>

<!-- R syntax highlighter -->
<script type="text/javascript">
var hljs=new function(){function m(p){return p.replace(/&/gm,"&amp;").replace(/</gm,"&lt;")}function f(r,q,p){return RegExp(q,"m"+(r.cI?"i":"")+(p?"g":""))}function b(r){for(var p=0;p<r.childNodes.length;p++){var q=r.childNodes[p];if(q.nodeName=="CODE"){return q}if(!(q.nodeType==3&&q.nodeValue.match(/\s+/))){break}}}function h(t,s){var p="";for(var r=0;r<t.childNodes.length;r++){if(t.childNodes[r].nodeType==3){var q=t.childNodes[r].nodeValue;if(s){q=q.replace(/\n/g,"")}p+=q}else{if(t.childNodes[r].nodeName=="BR"){p+="\n"}else{p+=h(t.childNodes[r])}}}if(/MSIE [678]/.test(navigator.userAgent)){p=p.replace(/\r/g,"\n")}return p}function a(s){var r=s.className.split(/\s+/);r=r.concat(s.parentNode.className.split(/\s+/));for(var q=0;q<r.length;q++){var p=r[q].replace(/^language-/,"");if(e[p]){return p}}}function c(q){var p=[];(function(s,t){for(var r=0;r<s.childNodes.length;r++){if(s.childNodes[r].nodeType==3){t+=s.childNodes[r].nodeValue.length}else{if(s.childNodes[r].nodeName=="BR"){t+=1}else{if(s.childNodes[r].nodeType==1){p.push({event:"start",offset:t,node:s.childNodes[r]});t=arguments.callee(s.childNodes[r],t);p.push({event:"stop",offset:t,node:s.childNodes[r]})}}}}return t})(q,0);return p}function k(y,w,x){var q=0;var z="";var s=[];function u(){if(y.length&&w.length){if(y[0].offset!=w[0].offset){return(y[0].offset<w[0].offset)?y:w}else{return w[0].event=="start"?y:w}}else{return y.length?y:w}}function t(D){var A="<"+D.nodeName.toLowerCase();for(var B=0;B<D.attributes.length;B++){var C=D.attributes[B];A+=" "+C.nodeName.toLowerCase();if(C.value!==undefined&&C.value!==false&&C.value!==null){A+='="'+m(C.value)+'"'}}return A+">"}while(y.length||w.length){var v=u().splice(0,1)[0];z+=m(x.substr(q,v.offset-q));q=v.offset;if(v.event=="start"){z+=t(v.node);s.push(v.node)}else{if(v.event=="stop"){var p,r=s.length;do{r--;p=s[r];z+=("</"+p.nodeName.toLowerCase()+">")}while(p!=v.node);s.splice(r,1);while(r<s.length){z+=t(s[r]);r++}}}}return z+m(x.substr(q))}function j(){function q(x,y,v){if(x.compiled){return}var u;var s=[];if(x.k){x.lR=f(y,x.l||hljs.IR,true);for(var w in x.k){if(!x.k.hasOwnProperty(w)){continue}if(x.k[w] instanceof Object){u=x.k[w]}else{u=x.k;w="keyword"}for(var r in u){if(!u.hasOwnProperty(r)){continue}x.k[r]=[w,u[r]];s.push(r)}}}if(!v){if(x.bWK){x.b="\\b("+s.join("|")+")\\s"}x.bR=f(y,x.b?x.b:"\\B|\\b");if(!x.e&&!x.eW){x.e="\\B|\\b"}if(x.e){x.eR=f(y,x.e)}}if(x.i){x.iR=f(y,x.i)}if(x.r===undefined){x.r=1}if(!x.c){x.c=[]}x.compiled=true;for(var t=0;t<x.c.length;t++){if(x.c[t]=="self"){x.c[t]=x}q(x.c[t],y,false)}if(x.starts){q(x.starts,y,false)}}for(var p in e){if(!e.hasOwnProperty(p)){continue}q(e[p].dM,e[p],true)}}function d(B,C){if(!j.called){j();j.called=true}function q(r,M){for(var L=0;L<M.c.length;L++){if((M.c[L].bR.exec(r)||[null])[0]==r){return M.c[L]}}}function v(L,r){if(D[L].e&&D[L].eR.test(r)){return 1}if(D[L].eW){var M=v(L-1,r);return M?M+1:0}return 0}function w(r,L){return L.i&&L.iR.test(r)}function K(N,O){var M=[];for(var L=0;L<N.c.length;L++){M.push(N.c[L].b)}var r=D.length-1;do{if(D[r].e){M.push(D[r].e)}r--}while(D[r+1].eW);if(N.i){M.push(N.i)}return f(O,M.join("|"),true)}function p(M,L){var N=D[D.length-1];if(!N.t){N.t=K(N,E)}N.t.lastIndex=L;var r=N.t.exec(M);return r?[M.substr(L,r.index-L),r[0],false]:[M.substr(L),"",true]}function z(N,r){var L=E.cI?r[0].toLowerCase():r[0];var M=N.k[L];if(M&&M instanceof Array){return M}return false}function F(L,P){L=m(L);if(!P.k){return L}var r="";var O=0;P.lR.lastIndex=0;var M=P.lR.exec(L);while(M){r+=L.substr(O,M.index-O);var N=z(P,M);if(N){x+=N[1];r+='<span class="'+N[0]+'">'+M[0]+"</span>"}else{r+=M[0]}O=P.lR.lastIndex;M=P.lR.exec(L)}return r+L.substr(O,L.length-O)}function J(L,M){if(M.sL&&e[M.sL]){var r=d(M.sL,L);x+=r.keyword_count;return r.value}else{return F(L,M)}}function I(M,r){var L=M.cN?'<span class="'+M.cN+'">':"";if(M.rB){y+=L;M.buffer=""}else{if(M.eB){y+=m(r)+L;M.buffer=""}else{y+=L;M.buffer=r}}D.push(M);A+=M.r}function G(N,M,Q){var R=D[D.length-1];if(Q){y+=J(R.buffer+N,R);return false}var P=q(M,R);if(P){y+=J(R.buffer+N,R);I(P,M);return P.rB}var L=v(D.length-1,M);if(L){var O=R.cN?"</span>":"";if(R.rE){y+=J(R.buffer+N,R)+O}else{if(R.eE){y+=J(R.buffer+N,R)+O+m(M)}else{y+=J(R.buffer+N+M,R)+O}}while(L>1){O=D[D.length-2].cN?"</span>":"";y+=O;L--;D.length--}var r=D[D.length-1];D.length--;D[D.length-1].buffer="";if(r.starts){I(r.starts,"")}return R.rE}if(w(M,R)){throw"Illegal"}}var E=e[B];var D=[E.dM];var A=0;var x=0;var y="";try{var s,u=0;E.dM.buffer="";do{s=p(C,u);var t=G(s[0],s[1],s[2]);u+=s[0].length;if(!t){u+=s[1].length}}while(!s[2]);if(D.length>1){throw"Illegal"}return{r:A,keyword_count:x,value:y}}catch(H){if(H=="Illegal"){return{r:0,keyword_count:0,value:m(C)}}else{throw H}}}function g(t){var p={keyword_count:0,r:0,value:m(t)};var r=p;for(var q in e){if(!e.hasOwnProperty(q)){continue}var s=d(q,t);s.language=q;if(s.keyword_count+s.r>r.keyword_count+r.r){r=s}if(s.keyword_count+s.r>p.keyword_count+p.r){r=p;p=s}}if(r.language){p.second_best=r}return p}function i(r,q,p){if(q){r=r.replace(/^((<[^>]+>|\t)+)/gm,function(t,w,v,u){return w.replace(/\t/g,q)})}if(p){r=r.replace(/\n/g,"<br>")}return r}function n(t,w,r){var x=h(t,r);var v=a(t);var y,s;if(v){y=d(v,x)}else{return}var q=c(t);if(q.length){s=document.createElement("pre");s.innerHTML=y.value;y.value=k(q,c(s),x)}y.value=i(y.value,w,r);var u=t.className;if(!u.match("(\\s|^)(language-)?"+v+"(\\s|$)")){u=u?(u+" "+v):v}if(/MSIE [678]/.test(navigator.userAgent)&&t.tagName=="CODE"&&t.parentNode.tagName=="PRE"){s=t.parentNode;var p=document.createElement("div");p.innerHTML="<pre><code>"+y.value+"</code></pre>";t=p.firstChild.firstChild;p.firstChild.cN=s.cN;s.parentNode.replaceChild(p.firstChild,s)}else{t.innerHTML=y.value}t.className=u;t.result={language:v,kw:y.keyword_count,re:y.r};if(y.second_best){t.second_best={language:y.second_best.language,kw:y.second_best.keyword_count,re:y.second_best.r}}}function o(){if(o.called){return}o.called=true;var r=document.getElementsByTagName("pre");for(var p=0;p<r.length;p++){var q=b(r[p]);if(q){n(q,hljs.tabReplace)}}}function l(){if(window.addEventListener){window.addEventListener("DOMContentLoaded",o,false);window.addEventListener("load",o,false)}else{if(window.attachEvent){window.attachEvent("onload",o)}else{window.onload=o}}}var e={};this.LANGUAGES=e;this.highlight=d;this.highlightAuto=g;this.fixMarkup=i;this.highlightBlock=n;this.initHighlighting=o;this.initHighlightingOnLoad=l;this.IR="[a-zA-Z][a-zA-Z0-9_]*";this.UIR="[a-zA-Z_][a-zA-Z0-9_]*";this.NR="\\b\\d+(\\.\\d+)?";this.CNR="\\b(0[xX][a-fA-F0-9]+|(\\d+(\\.\\d*)?|\\.\\d+)([eE][-+]?\\d+)?)";this.BNR="\\b(0b[01]+)";this.RSR="!|!=|!==|%|%=|&|&&|&=|\\*|\\*=|\\+|\\+=|,|\\.|-|-=|/|/=|:|;|<|<<|<<=|<=|=|==|===|>|>=|>>|>>=|>>>|>>>=|\\?|\\[|\\{|\\(|\\^|\\^=|\\||\\|=|\\|\\||~";this.ER="(?![\\s\\S])";this.BE={b:"\\\\.",r:0};this.ASM={cN:"string",b:"'",e:"'",i:"\\n",c:[this.BE],r:0};this.QSM={cN:"string",b:'"',e:'"',i:"\\n",c:[this.BE],r:0};this.CLCM={cN:"comment",b:"//",e:"$"};this.CBLCLM={cN:"comment",b:"/\\*",e:"\\*/"};this.HCM={cN:"comment",b:"#",e:"$"};this.NM={cN:"number",b:this.NR,r:0};this.CNM={cN:"number",b:this.CNR,r:0};this.BNM={cN:"number",b:this.BNR,r:0};this.inherit=function(r,s){var p={};for(var q in r){p[q]=r[q]}if(s){for(var q in s){p[q]=s[q]}}return p}}();hljs.LANGUAGES.cpp=function(){var a={keyword:{"false":1,"int":1,"float":1,"while":1,"private":1,"char":1,"catch":1,"export":1,virtual:1,operator:2,sizeof:2,dynamic_cast:2,typedef:2,const_cast:2,"const":1,struct:1,"for":1,static_cast:2,union:1,namespace:1,unsigned:1,"long":1,"throw":1,"volatile":2,"static":1,"protected":1,bool:1,template:1,mutable:1,"if":1,"public":1,friend:2,"do":1,"return":1,"goto":1,auto:1,"void":2,"enum":1,"else":1,"break":1,"new":1,extern:1,using:1,"true":1,"class":1,asm:1,"case":1,typeid:1,"short":1,reinterpret_cast:2,"default":1,"double":1,register:1,explicit:1,signed:1,typename:1,"try":1,"this":1,"switch":1,"continue":1,wchar_t:1,inline:1,"delete":1,alignof:1,char16_t:1,char32_t:1,constexpr:1,decltype:1,noexcept:1,nullptr:1,static_assert:1,thread_local:1,restrict:1,_Bool:1,complex:1},built_in:{std:1,string:1,cin:1,cout:1,cerr:1,clog:1,stringstream:1,istringstream:1,ostringstream:1,auto_ptr:1,deque:1,list:1,queue:1,stack:1,vector:1,map:1,set:1,bitset:1,multiset:1,multimap:1,unordered_set:1,unordered_map:1,unordered_multiset:1,unordered_multimap:1,array:1,shared_ptr:1}};return{dM:{k:a,i:"</",c:[hljs.CLCM,hljs.CBLCLM,hljs.QSM,{cN:"string",b:"'\\\\?.",e:"'",i:"."},{cN:"number",b:"\\b(\\d+(\\.\\d*)?|\\.\\d+)(u|U|l|L|ul|UL|f|F)"},hljs.CNM,{cN:"preprocessor",b:"#",e:"$"},{cN:"stl_container",b:"\\b(deque|list|queue|stack|vector|map|set|bitset|multiset|multimap|unordered_map|unordered_set|unordered_multiset|unordered_multimap|array)\\s*<",e:">",k:a,r:10,c:["self"]}]}}}();hljs.LANGUAGES.r={dM:{c:[hljs.HCM,{cN:"number",b:"\\b0[xX][0-9a-fA-F]+[Li]?\\b",e:hljs.IMMEDIATE_RE,r:0},{cN:"number",b:"\\b\\d+(?:[eE][+\\-]?\\d*)?L\\b",e:hljs.IMMEDIATE_RE,r:0},{cN:"number",b:"\\b\\d+\\.(?!\\d)(?:i\\b)?",e:hljs.IMMEDIATE_RE,r:1},{cN:"number",b:"\\b\\d+(?:\\.\\d*)?(?:[eE][+\\-]?\\d*)?i?\\b",e:hljs.IMMEDIATE_RE,r:0},{cN:"number",b:"\\.\\d+(?:[eE][+\\-]?\\d*)?i?\\b",e:hljs.IMMEDIATE_RE,r:1},{cN:"keyword",b:"(?:tryCatch|library|setGeneric|setGroupGeneric)\\b",e:hljs.IMMEDIATE_RE,r:10},{cN:"keyword",b:"\\.\\.\\.",e:hljs.IMMEDIATE_RE,r:10},{cN:"keyword",b:"\\.\\.\\d+(?![\\w.])",e:hljs.IMMEDIATE_RE,r:10},{cN:"keyword",b:"\\b(?:function)",e:hljs.IMMEDIATE_RE,r:2},{cN:"keyword",b:"(?:if|in|break|next|repeat|else|for|return|switch|while|try|stop|warning|require|attach|detach|source|setMethod|setClass)\\b",e:hljs.IMMEDIATE_RE,r:1},{cN:"literal",b:"(?:NA|NA_integer_|NA_real_|NA_character_|NA_complex_)\\b",e:hljs.IMMEDIATE_RE,r:10},{cN:"literal",b:"(?:NULL|TRUE|FALSE|T|F|Inf|NaN)\\b",e:hljs.IMMEDIATE_RE,r:1},{cN:"identifier",b:"[a-zA-Z.][a-zA-Z0-9._]*\\b",e:hljs.IMMEDIATE_RE,r:0},{cN:"operator",b:"<\\-(?!\\s*\\d)",e:hljs.IMMEDIATE_RE,r:2},{cN:"operator",b:"\\->|<\\-",e:hljs.IMMEDIATE_RE,r:1},{cN:"operator",b:"%%|~",e:hljs.IMMEDIATE_RE},{cN:"operator",b:">=|<=|==|!=|\\|\\||&&|=|\\+|\\-|\\*|/|\\^|>|<|!|&|\\||\\$|:",e:hljs.IMMEDIATE_RE,r:0},{cN:"operator",b:"%",e:"%",i:"\\n",r:1},{cN:"identifier",b:"`",e:"`",r:0},{cN:"string",b:'"',e:'"',c:[hljs.BE],r:0},{cN:"string",b:"'",e:"'",c:[hljs.BE],r:0},{cN:"paren",b:"[[({\\])}]",e:hljs.IMMEDIATE_RE,r:0}]}};
hljs.initHighlightingOnLoad();
</script>




</head>

<body>
<h1>Create HTML page containing all package examples using knitr and markdown</h1>

<p>Yesterday, I was updating my website to include more information about some R packages I am working on. I wanted to create a page showing examples of the functionality that is available in each package. Now, I usually write a quite extensive amount of examples in the help pages, showing most of the functionality. A single page with the examples of each function in the package including the output would be a, although very simply, quite nice way to quickly demonstrate the functionality of the package.</p>

<p>This is not hard to do by hand. Simply copy the examples to an R markdown file, add <code>knitr</code> chunks and a title here and there and it should look good. But this seemed like something that would be nice to do every update, so I wanted to automate it. The results (which can be seen <a href="http://sachaepskamp.com/semPlot/examples">here</a> and <a href="http://sachaepskamp.com/qgraph/examples">here</a>) were quite nice, so I figured I maybe others could use these codes as well. Do keep in mind that these codes are hardly tested!</p>

<p>Below is the code for the function <code>examplePage</code>. It scans all of a packages <code>.Rd</code> files for an example section and extracts them. The function creates and compiles a markdown document with the following title levels:</p>

<ol>
<li>The package name (only at the top)</li>
<li>The help-file name</li>
<li>Any line in the example section that contain word characters and either starts with three or more <code>#</code>s or starts with an <code>#</code> and ends with an <code>#</code> or <code>-</code>. </li>
<li>Any line that starts with (after spaces) exactly <code>##</code>, followed by word characters and does not end on <code>#</code> or <code>-</code>.</li>
</ol>

<p>These titles are chosen specifically such that the <code>control-shift-R</code> command in RStudio or something like <code>#### BIG SECTION ####</code>results in a large title.</p>

<h3>Usage:</h3>

<p><code>examplePage</code> has the following arguments:</p>

<ul>
<li><code>pkg</code>: Path to the package folder, should include a directory <code>man</code> with the <code>Rd</code> files.</li>
<li><code>openChunk</code>: code to open chunks. Defaults to <code>&quot;</code><code>{r, message=FALSE, warning = FALSE, error = FALSE}&quot;</code>. This can be used to enter more knitr options.</li>
<li><code>includeDontshow</code>: Logical stating if <code>don&#39;t show</code> environments should be included in the codes. Defaults to <code>FALSE</code>.</li>
<li><code>includeDontrun</code>: Logical stating if <code>don&#39;t run</code> environments should be included in the codes. Defaults to <code>TRUE</code>.</li>
</ul>

<h2>The function:</h2>

<pre><code class="r">examplePage &lt;- function(pkg, openChunk = &quot;```{r, message=FALSE, warning = FALSE, error = FALSE}&quot;, 
    includeDontshow = FALSE, includeDontrun = TRUE, exclude) {
    if (!require(&quot;knitr&quot;)) 
        stop(&quot;&#39;knitr must be intalled.&quot;)
    if (!require(&quot;markdown&quot;)) 
        stop(&quot;&#39;knitr must be intalled.&quot;)

    # Inner function to find closing brackets:
    findClose &lt;- function(x, openLoc, open = &quot;\\{&quot;, close = &quot;\\}&quot;) {
        # Find close:
        nest &lt;- 1
        i &lt;- openLoc + 1
        repeat {
            # If open bracket in line:
            if (grepl(open, x[i])) {
                nest &lt;- nest + length(gregexpr(open, x[i])[[1]])
            }
            if (grepl(close, x[i])) {
                nest &lt;- nest - length(gregexpr(close, x[i])[[1]])
            }
            if (nest == 0) 
                break
            i &lt;- i + 1
        }
        return(i)
    }

    files &lt;- list.files(paste0(pkg, &quot;/man&quot;), pattern = &quot;\\.Rd$&quot;, ignore.case = TRUE, 
        full.names = TRUE)

    # Exclude:
    if (!missing(exclude)) 
        files &lt;- files[!grepl(exclude, files)]

    # Preparation:
    n &lt;- length(files)
    subs &lt;- character(n)

    # For each rd file:
    for (i in seq_along(files)) {
        # Read file:
        txt &lt;- readLines(files[i])

        # Only include if there is only one example section:
        if (sum(grepl(&quot;\\\\examples\\{&quot;, txt)) == 1) {
            # Extract examples section:
            start &lt;- grep(&quot;\\\\examples\\{&quot;, txt)
            end &lt;- findClose(txt, start)
            txt &lt;- txt[(start + 1):(end - 1)]

            # Don&#39;t show fields:
            dontshows &lt;- grep(&quot;\\\\dontshow\\{&quot;, txt)
            if (length(dontshows) &gt; 0) {
                ends &lt;- numeric(length(dontshows))
                for (k in seq_along(dontshows)) {
                  ends[k] &lt;- findClose(txt, dontshows[k])
                }

                # Remove:
                if (includeDontshow) {
                  txt &lt;- txt[-c(dontshows, ends)]
                } else txt &lt;- txt[-do.call(c, mapply(dontshows, ends, FUN = &quot;:&quot;, 
                  SIMPLIFY = FALSE))]
            }

            # Don&#39;t run fields:
            dontruns &lt;- grep(&quot;\\\\dontrun\\{&quot;, txt)
            if (length(dontruns) &gt; 0) {
                ends &lt;- numeric(length(dontruns))
                for (k in seq_along(dontruns)) {
                  ends[k] &lt;- findClose(txt, dontruns[k])
                }

                # Remove:
                if (includeDontrun) {
                  txt &lt;- txt[-c(dontruns, ends)]
                } else txt &lt;- txt[-do.call(c, mapply(dontruns, ends, FUN = &quot;:&quot;, 
                  SIMPLIFY = FALSE))]
            }

            # Enter main title and first R chunk:
            txt &lt;- c(paste(&quot;##&quot;, gsub(&quot;\\.rd$&quot;, &quot;&quot;, basename(files[i]), ignore.case = TRUE)), 
                openChunk, txt, &quot;```&quot;)

            # Crawl over lines. If a title is encountered, close chunk and replace
            # title with markdown:
            j &lt;- 3
            repeat {
                # Small section (start with exactly two hashes, does not end with nonword:
                if (grepl(&quot;^\\s*##\\s*(\\w|\\s)+$&quot;, txt[j])) {
                  txt[j] &lt;- gsub(&quot;^\\s*##\\s*&quot;, &quot;#### &quot;, txt[j])
                  txt &lt;- c(txt[1:(j - 1)], &quot;```&quot;, txt[j], openChunk, txt[(j + 
                    1):length(txt)])
                  j &lt;- j + 2

                  # Else large section, starts with #, ends with nonchar, or starts with
                  # more than 2 #&#39;s
                } else if (grepl(&quot;\\w&quot;, txt[j]) &amp; (grepl(&quot;^\\s*###&quot;, txt[j]) | 
                  grepl(&quot;^\\s*#.*[#-]\\s*$&quot;, txt[j]))) {
                  txt[j] &lt;- gsub(&quot;^\\W*(?=\\w)&quot;, &quot;### &quot;, txt[j], perl = TRUE)
                  txt[j] &lt;- gsub(&quot;(?&lt;=\\w)\\W*$&quot;, &quot;&quot;, txt[j], perl = TRUE)

                  txt &lt;- c(txt[1:(j - 1)], &quot;```&quot;, txt[j], openChunk, txt[(j + 
                    1):length(txt)])
                  j &lt;- j + 2
                } else if (grepl(&quot;^\\s*#\\W*$&quot;, txt[j])) {
                  # If start is comment and no words, remove:
                  txt &lt;- txt[-j]
                  j &lt;- j - 1
                }

                j &lt;- j + 1
                if (j &gt; length(txt)) 
                  break
            }

            emptySections &lt;- which(txt[-length(txt)] == openChunk &amp; txt[-1] == 
                &quot;```&quot;)
            if (length(emptySections) &gt; 0) 
                txt &lt;- txt[-c(emptySections, emptySections + 1)]

            txt &lt;- gsub(&quot;\\\\%&quot;, &quot;%&quot;, txt)
            subs[i] &lt;- paste(txt, collapse = &quot;\n&quot;)
        }
    }

    subs &lt;- subs[order(nchar(subs), decreasing = TRUE)]
    subs &lt;- c(paste0(&quot;# &quot;, basename(pkg), &quot;\n\n```{r,echo=FALSE,message=FALSE}\nlibrary(\&quot;&quot;, 
        basename(pkg), &quot;\&quot;)\n```&quot;), subs)

    # Write Rmd:
    RmdFile &lt;- paste0(basename(pkg), &quot;.Rmd&quot;)
    write(paste(subs, collapse = &quot;\n\n&quot;), RmdFile)

    # Knit:
    mdFile &lt;- gsub(&quot;Rmd&quot;, &quot;md&quot;, RmdFile)
    knit(RmdFile, mdFile)

    # Markdown:
    htmlFile &lt;- gsub(&quot;Rmd&quot;, &quot;html&quot;, RmdFile)
    markdownToHTML(mdFile, htmlFile)

    browseURL(htmlFile)

    return(htmlFile)
}
</code></pre>

</body>

</html>



]]></content:encoded>
			<wfw:commentRss>http://sachaepskamp.com/?feed=rss2&#038;p=515</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
		<item>
		<title>qgraph version 1.1.0 and how to simply make a GUI using &#8216;rpanel&#8217;</title>
		<link>http://sachaepskamp.com/?p=351</link>
		<comments>http://sachaepskamp.com/?p=351#comments</comments>
		<pubDate>Mon, 24 Sep 2012 12:52:01 +0000</pubDate>
		<dc:creator>sachaepskamp</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[qgraph]]></category>
		<category><![CDATA[R]]></category>

		<guid isPermaLink="false">http://sachaepskamp.com/?p=351</guid>
		<description><![CDATA[Last week I have updated the &#8216;qgraph&#8216; package to version 1.1.0, available on CRAN now. Besides some internal changes (especially the self-loops have been substantially improved) the most important change is the addition of a GUI interface, which can be &#8230; <a href="http://sachaepskamp.com/?p=351">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p>Last week I have updated the &#8216;<a href="http://sachaepskamp.com/qgraph">qgraph</a>&#8216; package to version 1.1.0, available on <a href="http://cran.r-project.org/web/packages/qgraph/index.html">CRAN</a> now. Besides some internal changes (especially the self-loops have been substantially improved) the most important change is the addition of a GUI interface, which can be called using the argument gui=TRUE. For example:</p>
<pre>
data(big5)
data(big5groups)
qgraph(cor(big5),groups=big5groups,gui=TRUE)
</pre>
<p>Will open a plotting window and the GUI that allows the user to set several parameters before plotting:</p>
<div id="attachment_353" class="wp-caption aligncenter" style="width: 650px"><a href="http://sachaepskamp.com/wp-content/uploads/2012/09/qgraphGUI1.png"><img class="size-large wp-image-353" title="qgraphGUI" src="http://sachaepskamp.com/wp-content/uploads/2012/09/qgraphGUI1-1024x726.png" alt="" width="640" height="453" /></a><p class="wp-caption-text">Graphical User Interface for qgraph</p></div>
<p>There is also a simplified version of this GUI for regular graphs (not correlation matrices).</p>
<p>What I particularly like about this GUI is that it took me only one day to implement. Making a GUI for qgraph has been on my to do list for a long time, but I never really got to learning how one of the packages that allow this work. When I found out about the &#8216;<a href="http://www.stats.gla.ac.uk/~adrian/rpanel/">rpanel</a>&#8216; package (which is build on &#8216;tcltk&#8217;) I was pleasantly amazed with how simple and intuitive it was to use.</p>
<p>In short, the way &#8216;rpanel&#8217; works is by making a &#8216;panel&#8217; using &#8216;rp.control()&#8217; which is basically a list and also opens an empty GUI frame. We can use functions such as &#8216;rp.checkbox&#8217; and &#8216;rp.slider&#8217; to add elements to the GUI. Using these elements then does two things: an element of the list is changed (e.g., the element &#8216;xlim&#8217;), and a function is called on the list. This way, we can easily make an appropriate GUI element for each argument we need in a plotting function and make buttons that plot, save to PDF, etcetera.</p>
<p>To illustrate this I wrote a small function with comments that uses &#8216;plot.default&#8217; to plot a scatter plot, and adds a small GUI frame allowing a user to zoom into the scatter plot. The codes can be downloaded <a href="http://www.sachaepskamp.com/files/ScatterZoom.R">here</a>. A small example:</p>
<pre>
x <- rnorm(100)
y <- x + rnorm(100)
ScatterZoom(x,y)
</pre>
<p>More information on 'rpanel' can be found in its <a href="http://www.jstatsoft.org/v17/i09/">Journal of Statistical Software article</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://sachaepskamp.com/?feed=rss2&#038;p=351</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>NWO Research Talent</title>
		<link>http://sachaepskamp.com/?p=333</link>
		<comments>http://sachaepskamp.com/?p=333#comments</comments>
		<pubDate>Wed, 02 May 2012 04:51:35 +0000</pubDate>
		<dc:creator>sachaepskamp</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://sachaepskamp.com/?p=333</guid>
		<description><![CDATA[A more personal blog this time. I have been granted a research talent grant by the Netherlands Organisation for Scientific Research (NWO). In July I will start a three-year position as PhD-student at the University of Amsterdam, in which I will &#8230; <a href="http://sachaepskamp.com/?p=333">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p>A more personal blog this time. I have been granted a <a href="http://www.nwo.nl/nwohome.nsf/pages/NWOP_8HCJMR_Eng">research talent grant</a> by the Netherlands Organisation for Scientific Research (NWO). In July I will start a three-year position as PhD-student at the University of Amsterdam, in which I will continue <a href="http://sachaepskamp.com/publications">earlier work</a> on the use of networks and complex systems in psychology and psychometrics.</p>
]]></content:encoded>
			<wfw:commentRss>http://sachaepskamp.com/?feed=rss2&#038;p=333</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Music player in R (Linux)</title>
		<link>http://sachaepskamp.com/?p=324</link>
		<comments>http://sachaepskamp.com/?p=324#comments</comments>
		<pubDate>Sun, 26 Feb 2012 12:43:49 +0000</pubDate>
		<dc:creator>sachaepskamp</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[R]]></category>

		<guid isPermaLink="false">http://sachaepskamp.com/?p=324</guid>
		<description><![CDATA[Yesterday I found out about &#8216;mplayer&#8217;, which is a movie/music player for Unix that can be completely controlled from the terminal (http://www.mplayerhq.hu/). I started playing around with it while at the same time learning reference classes. The result, a music &#8230; <a href="http://sachaepskamp.com/?p=324">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p>Yesterday I found out about &#8216;mplayer&#8217;, which is a movie/music player for Unix that can be completely controlled from the terminal (http://www.mplayerhq.hu/). I started playing around with it while at the same time learning reference classes. The result, a music player in R!</p>
<p><a href="http://sachaem47.fortyseven.versio.nl/files/playlist.R">Code</a></p>
<p>It is very basic and abit buggy (mainly in displaying unwanted warning messages) but does seem to work. The code above (requires tcltk package) gives the reference class &#8220;playlist&#8221;. First we create a new empty playlist:</p>
<pre>
pl <- playlist$new()
</pre>
<p>Next we fill the playlist by manually adding music files:</p>
<pre>
pl$add()
</pre>
<p>or by importing all music files in a folder (recursively):</p>
<pre>
pl$dir()
</pre>
<p>Both open a gui window by default, but can be supplied a character with the locations as well.</p>
<p>Now we can shuffle the playlist if we want:</p>
<pre>
pl$shuffle()
</pre>
<p>Finally, start playing:</p>
<pre>
pl$play()
</pre>
<p>And if we don't want to listen anymore:</p>
<pre>
pl$stop()
</pre>
<p>Furthermore 'pause' can be used to pause playing, 'skip' to skip a song, 'step' to skip multiple songs and 'previous' to go back a song.</p>
<p>I have only tested this on a Linux computer (Ubuntu 11.10).</p>
]]></content:encoded>
			<wfw:commentRss>http://sachaepskamp.com/?feed=rss2&#038;p=324</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>10,000 R Questions on Stackoverflow</title>
		<link>http://sachaepskamp.com/?p=313</link>
		<comments>http://sachaepskamp.com/?p=313#comments</comments>
		<pubDate>Fri, 17 Feb 2012 09:59:57 +0000</pubDate>
		<dc:creator>sachaepskamp</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[R]]></category>

		<guid isPermaLink="false">http://sachaepskamp.com/?p=313</guid>
		<description><![CDATA[I was browsing stackoverflow when suddenly I noticed: 10 thousand questions tagged! I started using Stackoverflow almost exactly a year ago and remember that the counter was about 3 thousand at the time. It is a beautiful example of how fast the R community is &#8230; <a href="http://sachaepskamp.com/?p=313">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p>I was browsing <a href="http://www.stackoverflow.com">stackoverflow</a> when suddenly I noticed:</p>
<p><a href="http://sachaepskamp.com/wp-content/uploads/2012/02/R10k.png"><img class="alignright size-large wp-image-314" title="R10k" src="http://sachaepskamp.com/wp-content/uploads/2012/02/R10k-1024x220.png" alt="" width="640" height="137" /></a></p>
<p>10 thousand questions tagged! I started using Stackoverflow almost exactly a year ago and remember that the counter was about 3 thousand at the time. It is a beautiful example of how fast the R community is growing.</p>
]]></content:encoded>
			<wfw:commentRss>http://sachaepskamp.com/?feed=rss2&#038;p=313</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>The &#8216;swst&#8217; package to print statistical results in Sweave</title>
		<link>http://sachaepskamp.com/?p=210</link>
		<comments>http://sachaepskamp.com/?p=210#comments</comments>
		<pubDate>Wed, 23 Nov 2011 19:38:44 +0000</pubDate>
		<dc:creator>sachaepskamp</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[LaTeX]]></category>
		<category><![CDATA[R]]></category>

		<guid isPermaLink="false">http://sachaepskamp.com/?p=210</guid>
		<description><![CDATA[When I was making the slides for a lecture on using Sweave to incorporate R and LaTeX I was unpleasantly surprised at how tedious it can be to extract statistical values and print them in proper LaTeX code. For example, consider a &#8230; <a href="http://sachaepskamp.com/?p=210">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p>When I was making the slides for a lecture on using Sweave to incorporate R and LaTeX I was unpleasantly surprised at how tedious it can be to extract statistical values and print them in proper LaTeX code.</p>
<p>For example, consider a small toy dataset of lengths with 100 females have a normally distributed length with mean 170cm and standard deviation of 10, and 100 males with mean length of 180cm and standard deviation of 10:</p>
<pre>
R> foo <- data.frame(
length = c(rnorm(100,170,10), rnorm(100,180,10)),
sex = rep(c("female","male"),each=100))
</pre>
<p>A t-test shows that the means are different:</p>
<pre>R> t.test(length~sex,data=foo,var.equal=TRUE)

	Two Sample t-test

data:  length by sex
t = -6.8396, df = 198, p-value = 9.653e-11
alternative hypothesis: true difference in means is not equal to 0
95 percent confidence interval:
 -12.715980 -7.024375
sample estimates:
mean in group female   mean in group male
            170.2455           180.1157</pre>
<p>The t.test() function returns a "htest" class object which is commonly used in R and allows us to easily extract the statistic, degrees of freedom and p-value:</p>
<pre>R> res <- t.test(length~sex,data=foo,var.equal=TRUE)
R> res[['statistic']]
        t
-6.839605
R> res[['parameter']]
 df
198
R> res[['p.value']]
[1] 9.653065e-11</pre>
<p>Great, now we can reference the statistic in our Sweave document:</p>
<pre>Men were significantly taller than women
($t(\Sexpr{res[['parameter']]})=\Sexpr{res[['statistic']]}$,
$p=\Sexpr{res[['p.value']]}$)</pre>
<p>This returns: "Men were significantly taller than women (t(198) = −6.83960491494726,<br />
p = 9.65306549553569e − 11)". Obviously we need to round the values:</p>
<pre>Men were significantly taller than women
($t(\Sexpr{res[['parameter']]})=\Sexpr{round(res[['statistic']],3)}$,
$p=\Sexpr{round(res[['p.value']],3)}$)</pre>
<p>Which returns "Men were significantly taller than women (t(198) = −6.84, p = 0)". Better, but the p value should not be rounded to zero but rather be reported as being smaller than 0.001 or something similar if it is very small. To do this and make sure it stays dynamic an ifelse statement is needed:</p>
<pre>Men were significantly taller than women
($t(\Sexpr{res[['parameter']]})=\Sexpr{round(res[['statistic']],3)}$,
$p \Sexpr{ifelse(res[['p.value']]<0.001,'< 0.001',
   paste('=',round(res[['p.value']],3)))}$)</pre>
<p>Which returns "Men were significantly taller than women (t(198) = −6.84, p < 0.001)".</p>
<p>Good, but this sure was a lot of code to make this simple reference, and for some other classes extracting the statistics from the output object is also a lot harder than the "htest" class. For this reason I wrote the 'swst' package, which stands for SWeave STatistics.</p>
<p>'swst' has two main functions. The 'swp()' function can be used to generate proper LaTeX code with rounded numbers and inequality signs if needed given the name of a statistic, its value, optional degrees of freedom and the p-value. The 'swst()' function is an S3 generic with methods for a few commonly used object classes that extract the statistic, df, and p-value and send the results to 'swp()'.</p>
<p>This reduces the code to:</p>
<pre>Men were significantly taller than women \Sexpr{swst(res)}</pre>
<p>Which returns "Men were significantly taller than women (t(198) = −6.84, p < 0.001)". That's much less code!</p>
<p>I have written this package in a fairly short time and it is now very short and only supports a few objects. Help is greatly appreciated! If you know an object that needs to be implemented let me know or write your own method on:</p>
<p>http://github.com/SachaEpskamp/swst</p>
<p>The CRAN link is:</p>
<p>http://cran.r-project.org/web/packages/swst/index.html</p>
]]></content:encoded>
			<wfw:commentRss>http://sachaepskamp.com/?feed=rss2&#038;p=210</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Materials of the &#8220;LaTeX for Psychological Researchers&#8221; course</title>
		<link>http://sachaepskamp.com/?p=232</link>
		<comments>http://sachaepskamp.com/?p=232#comments</comments>
		<pubDate>Wed, 23 Nov 2011 18:51:09 +0000</pubDate>
		<dc:creator>sachaepskamp</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[LaTeX]]></category>
		<category><![CDATA[R]]></category>

		<guid isPermaLink="false">http://sachaepskamp.com/?p=232</guid>
		<description><![CDATA[I have given a course on using LaTeX for psychological researchers. This course consisted of four lectures in which I discussed the following subjects: how to obtain a LaTeX distribution How to use LaTeX to write professional scientific reports How to use &#8230; <a href="http://sachaepskamp.com/?p=232">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p>I have given a course on using LaTeX for psychological researchers. This course consisted of four lectures in which I discussed the following subjects:</p>
<ul>
<li>how to obtain a LaTeX distribution</li>
<li>How to use LaTeX to write professional scientific reports</li>
<li>How to use BibTeX and apacite to easily add references and completely automate the reference list</li>
<li>How to use the apa document class to produce articles in APA-style</li>
<li>How to use Beamer to produce presentation slides</li>
<li>How to use Sweave to incorperate R codes in your LaTeX document for reporting reproducible research</li>
</ul>
<p>The slides and examples as well as a lot of additional links can be found at:</p>
<p><a href="http://sachaepskamp.com/latex-course">http://sachaepskamp.com/latex-course</a></p>
]]></content:encoded>
			<wfw:commentRss>http://sachaepskamp.com/?feed=rss2&#038;p=232</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
