<?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/"
	xmlns:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>&#34;R&#34; you ready?</title>
	<atom:link href="http://ryouready.wordpress.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://ryouready.wordpress.com</link>
	<description>My advances in R - a learner's diary</description>
	<lastBuildDate>Fri, 24 May 2013 21:52:15 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain='ryouready.wordpress.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://s2.wp.com/i/buttonw-com.png</url>
		<title>&#34;R&#34; you ready?</title>
		<link>http://ryouready.wordpress.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://ryouready.wordpress.com/osd.xml" title="&#34;R&#34; you ready?" />
	<atom:link rel='hub' href='http://ryouready.wordpress.com/?pushpress=hub'/>
		<item>
		<title>Creating a text grob that automatically adjusts to viewport size</title>
		<link>http://ryouready.wordpress.com/2012/08/01/creating-a-text-grob-that-automatically-adjusts-to-viewport-size/</link>
		<comments>http://ryouready.wordpress.com/2012/08/01/creating-a-text-grob-that-automatically-adjusts-to-viewport-size/#comments</comments>
		<pubDate>Wed, 01 Aug 2012 14:06:32 +0000</pubDate>
		<dc:creator>markheckmann</dc:creator>
				<category><![CDATA[R / R-Code]]></category>

		<guid isPermaLink="false">http://ryouready.wordpress.com/?p=854</guid>
		<description><![CDATA[I recently wanted to construe a dashboard widget that contains some text and other elements using the grid graphics system. The size available for the widget will vary. When the sizes for the elements of the grobs in the widget are specified as Normalised Parent Coordinates the size adjustments happen automatically. Text does not automatically adjust though. The [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ryouready.wordpress.com&#038;blog=5891102&#038;post=854&#038;subd=ryouready&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p><a href="http://www.flickr.com/photos/lou/2231734109/"><img class="alignleft size-medium wp-image-917" style="margin:8px;" title="ames_illusion_flickr_saikofish_2231734109_with_source" src="http://ryouready.files.wordpress.com/2012/08/ames_illusion_flickr_saikofish_2231734109_with_source.jpg?w=300&#038;h=210" alt="Source: flickr, user saikofish, pic lou (http://www.flickr.com/photos/lou/2231734109/)" width="300" height="210" /></a></p>
<p>I recently wanted to construe a dashboard widget that contains some text and other elements using the grid graphics system. The size available for the widget will vary. When the sizes for the elements of the grobs in the widget are specified as <tt>Normalised Parent Coordinates</tt> the size adjustments happen automatically. Text does not automatically adjust though. The size of the text which is calculated as fontsize times the character expansion factor (<tt>cex</tt>) remains the same when the viewport size changes. For my widget this would require to adjust the fontsize or <tt>cex</tt> settings for each case seperately. While this is not really an obstacle, I asked myself how a grob that will adjust its text size automatically when being resized can be construed. Here I jot down my results in the hope that you may find this useful.<span id="more-854"></span></p>
<p>First I will create a new grob class called <tt>resizingTextGrob</tt> that is supposed to resize automatically.</p>
<pre class="brush: r; title: ; notranslate">
library(grid)
library(scales)

resizingTextGrob &amp;lt;- function(...)
{
  grob(tg=textGrob(...), cl=&amp;quot;resizingTextGrob&amp;quot;)
}
</pre>
<p>The grob created by the function contains nothing more than a <tt>textGrob</tt>. In order for the grob class to print something we need to specify the <tt>drawDetails</tt> method for our class which will do the drawing. The <tt>drawDetails</tt> method is called automatically when drawing a grob using <tt>grob.draw</tt>.</p>
<pre class="brush: r; title: ; notranslate">
drawDetails.resizingTextGrob &amp;lt;- function(x, recording=TRUE)
{
  grid.draw(x$tg)
}
</pre>
<p>Up to now this will produce the same results as a plain <tt>textGrob</tt>.</p>
<pre class="brush: r; title: ; notranslate">
g &amp;lt;- resizingTextGrob(label=&amp;quot;test 1&amp;quot;)
grid.draw(g)
grid.text(&amp;quot;test 2&amp;quot;, y=.4)
</pre>
<p style="text-align:center;"><a href="http://ryouready.files.wordpress.com/2012/08/resizing_text_grob_compare_1.png"><img class="aligncenter size-medium wp-image-876" style="border:0;" title="resizing_text_grob_compare_1" src="http://ryouready.files.wordpress.com/2012/08/resizing_text_grob_compare_1.png?w=300&#038;h=272" alt="" width="300" height="272" /></a></p>
<p>Now, before doing the drawing we want to calculate the size of the viewport and adjust the fontsize accordingly. To do this we can take the approach to push a new viewport with an adjusted fontsize before the drawing occurs. To perfom the calculations and and push the viewport we specify a <tt>preDrawDetails</tt> method. This method is automatically called before any drawing occures. It gives us the chance to do some modifications, like e.g. pushing a viewport.</p>
<p>For this purpose first the available height is calculated. Than the fontsize is rescaled according to the available width. The rescaled fontsize is used for the new viewport. Now for a fully developed class we will want to include these parameters in the grob constructor of course. Or we might define a proportion factor argument by which to shrink the text instead. Anyway, to keep things simple this is not done here.</p>
<pre class="brush: r; title: ; notranslate">
preDrawDetails.resizingTextGrob &amp;lt;- function(x)
{
  h &amp;lt;- convertHeight(unit(1, &amp;quot;snpc&amp;quot;), &amp;quot;mm&amp;quot;, valueOnly=TRUE)
  fs &amp;lt;- rescale(h, to=c(18, 7), from=c(120, 20))
  pushViewport(viewport(gp = gpar(fontsize = fs)))
}
</pre>
<p>To clean up after the drawing the created viewport is popped. This is done in the <tt>postDrawDetails</tt> which is automatically called after the <tt>drawDetails</tt> method.</p>
<pre class="brush: r; title: ; notranslate">
postDrawDetails.resizingTextGrob &amp;lt;- function(x)
  popViewport()
</pre>
<p>Now the output will depend on the size of the current viewport. When resizing the device the text size will adjust.</p>
<pre class="brush: r; title: ; notranslate">
g &amp;lt;- resizingTextGrob(label=&amp;quot;test 1&amp;quot;)
grid.draw(g)
grid.text(&amp;quot;test 2&amp;quot;, y=.4)
</pre>
<p style="text-align:center;"><a href="http://ryouready.files.wordpress.com/2012/08/resizing_text_grob_compare_2.png"><img class="aligncenter size-full wp-image-879" style="border:0;" title="resizing_text_grob_compare_2" src="http://ryouready.files.wordpress.com/2012/08/resizing_text_grob_compare_2.png?w=500" alt=""   /></a></p>
<p>Let&#8217;s compare the standard <tt>textGrob</tt> with the new class. For this purpose let&#8217;s draw a small clock and display it using different device sizes.</p>
<pre class="brush: r; title: ; notranslate">
library(gridExtra)
a &amp;lt;- seq(2*pi, 2*pi/ 12, length=12) + pi/3
x &amp;lt;- cos(a) / 2
y &amp;lt;- sin(a) / 2
segs &amp;lt;- segmentsGrob(x*.2 + .5, y*.2+.5, x*.3 + .5, y*.3 + .5)
# the standard approach
tgs.1 &amp;lt;- textGrob(1:12, x*.4 + .5, y*.4 + .5)
# the new grob class
tgs.2 &amp;lt;- resizingTextGrob(1:12, x*.4 + .5, y*.4 + .5)
grid.arrange(grobTree(segs, tgs.1), grobTree(segs, tgs.2))
</pre>
<p>What it looks like at the beginning.</p>
<p style="text-align:center;"><a href="http://ryouready.files.wordpress.com/2012/08/resizing_text_grob_compare_3.png"><img class="aligncenter size-full wp-image-880" style="border:0;" title="resizing_text_grob_compare_3" src="http://ryouready.files.wordpress.com/2012/08/resizing_text_grob_compare_3.png?w=500" alt=""   /></a></p>
<p>What it looks like when the device is resized.</p>
<p style="text-align:center;"><a href="http://ryouready.files.wordpress.com/2012/08/resizing_text_grob_compare_4.png"><img class="aligncenter size-full wp-image-881" style="border:0;" title="resizing_text_grob_compare_4" src="http://ryouready.files.wordpress.com/2012/08/resizing_text_grob_compare_4.png?w=500" alt=""   /></a></p>
<p>Note how the size of the text of the lower clock adjusts to the device size. The text size in the upper graphs remains the same and becomes too big for the clock while it changes for the lower ones.</p>
<p>BTW: The definitive guide for  the grid graphics model is the book <a href="http://www.stat.auckland.ac.nz/~paul/RGraphics/rgraphics.html" target="_blank">R graphics</a> by Paul Murrell.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/ryouready.wordpress.com/854/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/ryouready.wordpress.com/854/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ryouready.wordpress.com&#038;blog=5891102&#038;post=854&#038;subd=ryouready&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://ryouready.wordpress.com/2012/08/01/creating-a-text-grob-that-automatically-adjusts-to-viewport-size/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://2.gravatar.com/avatar/80731da9aeab670f39dfa6f74a306222?s=96&#38;d=http%3A%2F%2F2.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96" medium="image">
			<media:title type="html">markheckmann</media:title>
		</media:content>

		<media:content url="http://ryouready.files.wordpress.com/2012/08/ames_illusion_flickr_saikofish_2231734109_with_source.jpg?w=300" medium="image">
			<media:title type="html">ames_illusion_flickr_saikofish_2231734109_with_source</media:title>
		</media:content>

		<media:content url="http://ryouready.files.wordpress.com/2012/08/resizing_text_grob_compare_1.png?w=300" medium="image">
			<media:title type="html">resizing_text_grob_compare_1</media:title>
		</media:content>

		<media:content url="http://ryouready.files.wordpress.com/2012/08/resizing_text_grob_compare_2.png" medium="image">
			<media:title type="html">resizing_text_grob_compare_2</media:title>
		</media:content>

		<media:content url="http://ryouready.files.wordpress.com/2012/08/resizing_text_grob_compare_3.png" medium="image">
			<media:title type="html">resizing_text_grob_compare_3</media:title>
		</media:content>

		<media:content url="http://ryouready.files.wordpress.com/2012/08/resizing_text_grob_compare_4.png" medium="image">
			<media:title type="html">resizing_text_grob_compare_4</media:title>
		</media:content>
	</item>
		<item>
		<title>Useful R snippets</title>
		<link>http://ryouready.wordpress.com/2012/03/18/useful-r-snippets/</link>
		<comments>http://ryouready.wordpress.com/2012/03/18/useful-r-snippets/#comments</comments>
		<pubDate>Sun, 18 Mar 2012 17:56:32 +0000</pubDate>
		<dc:creator>markheckmann</dc:creator>
				<category><![CDATA[R / R-Code]]></category>

		<guid isPermaLink="false">http://ryouready.wordpress.com/?p=792</guid>
		<description><![CDATA[In this post we collect several R one- or few-liners that we consider useful. As our minds tend to forget these little fragments we jot them down here so we will find them again. Subsequently re-calling a function that takes two arguments Suppose we wanted to call a function that takes two arguments and use [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ryouready.wordpress.com&#038;blog=5891102&#038;post=792&#038;subd=ryouready&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p><a title="on flickr by user zzpza Jan 2012, http://www.flickr.com/photos/zzpza/3269784239/. THX!" href="http://ryouready.files.wordpress.com/2012/01/tools.jpg"><img class="alignleft size-full wp-image-817" style="margin:8px;" title="tools" src="http://ryouready.files.wordpress.com/2012/01/tools.jpg?w=500" alt="on flickr by user zzpza Jan 2012, http://www.flickr.com/photos/zzpza/3269784239/. THX!"   /></a>In this post we collect several R one- or few-liners that we consider useful. As our minds tend to forget these little fragments we jot them down here so we will find them again.<span id="more-792"></span></p>
<h3>Subsequently re-calling a function that takes two arguments</h3>
<p>Suppose we wanted to call a function that takes two arguments and use the results as a argument to the same function again. For example may want to sum up the values 1 to 5 Of course the function <tt>sum</tt> will do this for us, but what if this function didn&#8217;t exist? We might of course write:</p>
<pre class="brush: r; title: ; notranslate">
1 + 2 + 3 + 4 + 5
</pre>
<p>But how do that in a single function call? Using <tt>do.call</tt> or the like will not work, as the function <tt>"+"</tt> takes two arguments.</p>
<pre class="brush: r; title: ; notranslate">
do.call(&quot;+&quot;, list(1:5))
</pre>
<p>The trick is to use the function <tt>Reduce</tt>.</p>
<pre class="brush: r; title: ; notranslate">
Reduce(&quot;+&quot;, 1:5)
&gt; 15
</pre>
<h3>Evaluating an R command stored in a character string</h3>
<p>From time to time, you may encounter situations where you have to evaluate a command which is stored in a character string. For example, let&#8217;s assume that we have the following variables:</p>
<pre class="brush: r; title: ; notranslate">
name1 &lt;- &quot;Steve&quot;
name2 &lt;- &quot;Bill&quot;
value1 &lt;- 1
value2 &lt;- 0
</pre>
<p>Now, what would you do if you have to create a vector with entries whose value is stored in the variables <tt>value1</tt> and <tt>value2</tt> and entry names whose value is stored in the variables <tt>name1</tt> and <tt>name2</tt>? You can write:</p>
<pre class="brush: r; title: ; notranslate">
command &lt;- paste(&quot;values=c(&quot;,name1,&quot;=&quot;,value1,&quot;,&quot;,
name2,&quot;=&quot;,value2,&quot;)&quot;,sep=&quot;&quot;)
values &lt;- eval(parse(text=command))
</pre>
<p>After issuing those command a vector named <tt>values </tt>is going to be created with named entries and values as follows</p>
<pre class="brush: r; title: ; notranslate">
Steve  Bill
1     0
</pre>
<h3>Creating an empty dataframe with zero rows</h3>
<p>Sometimes I want to fill up a dataframe from the frist row on. It might be useful do start off with a dataframe with zero rows for that purpose. The function <tt>numeric</tt> or <tt>character</tt> do the job. In case we wanted to specify a factor with predefined levels also <tt>factor</tt> may be useful.</p>
<pre class="brush: r; title: ; notranslate">
data.frame(a=numeric(), b=numeric())
data.frame(a=numeric(), b=character(), c=factor(levels=1:10), stringsAsFactors=F)
</pre>
<p>&#8230; to be continued.</p>
<p>Tamas and Mark</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/ryouready.wordpress.com/792/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/ryouready.wordpress.com/792/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ryouready.wordpress.com&#038;blog=5891102&#038;post=792&#038;subd=ryouready&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://ryouready.wordpress.com/2012/03/18/useful-r-snippets/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
	
		<media:content url="http://2.gravatar.com/avatar/80731da9aeab670f39dfa6f74a306222?s=96&#38;d=http%3A%2F%2F2.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96" medium="image">
			<media:title type="html">markheckmann</media:title>
		</media:content>

		<media:content url="http://ryouready.files.wordpress.com/2012/01/tools.jpg" medium="image">
			<media:title type="html">tools</media:title>
		</media:content>
	</item>
		<item>
		<title>multi-platform real-time &#8216;intro&#8217; in R using rdyncall</title>
		<link>http://ryouready.wordpress.com/2011/07/29/multi-platform-intro-video-scripted-in-r-using-rdyncall/</link>
		<comments>http://ryouready.wordpress.com/2011/07/29/multi-platform-intro-video-scripted-in-r-using-rdyncall/#comments</comments>
		<pubDate>Fri, 29 Jul 2011 18:01:13 +0000</pubDate>
		<dc:creator>markheckmann</dc:creator>
				<category><![CDATA[R / R-Code]]></category>
		<category><![CDATA[intro]]></category>
		<category><![CDATA[R]]></category>

		<guid isPermaLink="false">http://ryouready.wordpress.com/?p=765</guid>
		<description><![CDATA[Guest post by Daniel Adler. Below is a real-time audio-visual multimedia demonstration &#8211; or in short &#8216;an intro&#8217; &#8211; written in 100% pure R. It requires no compilation and runs across major platforms via the package rdyncall and preinstalled precompiled standard libraries such as OpenGL and SDL libraries. This &#8216;happy-birthday&#8217; production runs about 3 minutes [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ryouready.wordpress.com&#038;blog=5891102&#038;post=765&#038;subd=ryouready&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p><a href="http://ryouready.files.wordpress.com/2011/07/sousalicious4-320x240.png"><img class="alignleft size-medium wp-image-768" style="margin:7px 10px;" title="sousalicious4-320x240" src="http://ryouready.files.wordpress.com/2011/07/sousalicious4-320x240.png?w=300&#038;h=225" alt="" width="300" height="225" /></a>Guest post by <a href="http://www.statoek.wiso.uni-goettingen.de/cms/user/index.php?lang=de&amp;section=institut.team.dadler" target="_blank">Daniel Adler</a>.</p>
<p>Below is a real-time audio-visual multimedia demonstration &#8211; or in short &#8216;an intro&#8217; &#8211; written in 100% pure R. It requires no compilation and runs across major platforms via the package <a href="http://cran.r-project.org/web/packages/rdyncall/index.html" target="_blank">rdyncall</a> and preinstalled precompiled standard libraries such as OpenGL and SDL libraries. This &#8216;happy-birthday&#8217; production runs about 3 minutes and comprises typical effects of the home computer oldschool demoscene era such as a rotating cube, multi-layer star field, text scrollers, still images and flashes while playing a nice Amiga Soundtracker module tune. Check out the video screen-cast (with sound) or enjoy a smooth framerate using the R version at <a href="http://dyncall.org/demos/soulsalicious/" target="_blank">this website</a>.</p>
<p><span id="more-765"></span><div class='embed-vimeo' style='text-align:center;'><iframe src='http://player.vimeo.com/video/27059431' width='400' height='300' frameborder='0'></iframe></div></p>
<p>The <a href="http://cran.r-project.org/web/packages/rdyncall/index.html" target="_blank">rdyncall</a> package used for this video facilitates a dynamic middleware between R and  C libraries and offers an improved Foreign Function Interface for R. It enables developers to &#8216;script&#8217; system-level code in R such as OpenGL visualizations, multimedia applications, computer games or simply to call a single system service without the need for writing C code. The FFI toolkit offered by the package is flexible enough to address low-level C interfacing issues directly in R. R bindings to the C libraries are created dynamically with a single interface function &#8216;dynport&#8217; similar to &#8216;library&#8217; and the C interface is made available in R as if it is an extension to the language. Support for handling foreign C data types and callbacks is offered by helper utilities. An extendable repository of cross-platform bindings is delivered with the package that contains bindings to OpenGL 1, OpenGL 3, SDL, Expat, ODE, CUDA, OpenCL and more.</p>
<p>The implementation of <a href="http://cran.r-project.org/web/packages/rdyncall/index.html" target="_blank">rdyncall</a> is based on libraries of the <a href="http://dyncall.org">DynCall</a> project that offers a dynamic call facility between interpreted languages and precompiled native code with support for almost all basic C types (in constrast to &#8216;.C&#8217; in R). Call kernels &#8211; implemented in Assembly &#8211; offer a Foreign Function Interface solution that is small in size and generic in its application. The libraries have been ported across a large set of processor architectures (i386,AMD64,ARM,PowerPC 32-bit, MIPS 32/64-bit, SPARC 32/64-bit) and operating-systems including major R platforms.</p>
<p>The <a href="http://cran.r-project.org/web/packages/rdyncall/index.html" target="_blank">rdyncall </a>package comes with a couple of demos, a comprehensive manual and vignette that gives further details.</p>
<p>Have fun!</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/ryouready.wordpress.com/765/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/ryouready.wordpress.com/765/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ryouready.wordpress.com&#038;blog=5891102&#038;post=765&#038;subd=ryouready&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://ryouready.wordpress.com/2011/07/29/multi-platform-intro-video-scripted-in-r-using-rdyncall/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
	
		<media:content url="http://2.gravatar.com/avatar/80731da9aeab670f39dfa6f74a306222?s=96&#38;d=http%3A%2F%2F2.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96" medium="image">
			<media:title type="html">markheckmann</media:title>
		</media:content>

		<media:content url="http://ryouready.files.wordpress.com/2011/07/sousalicious4-320x240.png?w=300" medium="image">
			<media:title type="html">sousalicious4-320x240</media:title>
		</media:content>
	</item>
		<item>
		<title>Using R, Sweave and Latex to integrate animations into PDFs</title>
		<link>http://ryouready.wordpress.com/2011/04/18/using-r-sweave-and-latex-to-integrate-animations-into-pdfs/</link>
		<comments>http://ryouready.wordpress.com/2011/04/18/using-r-sweave-and-latex-to-integrate-animations-into-pdfs/#comments</comments>
		<pubDate>Mon, 18 Apr 2011 14:16:35 +0000</pubDate>
		<dc:creator>markheckmann</dc:creator>
				<category><![CDATA[R / R-Code]]></category>

		<guid isPermaLink="false">http://ryouready.wordpress.com/?p=690</guid>
		<description><![CDATA[The first week of April I attended an excellent workshop on biplots held by Michael Greenacre and Oleg Nenadić at the Gesis Institute in Cologne, Germany. Throughout his presentations, Michael used animations to visualize the concepts he was explaining. He also included  animations in some of his papers. This inspired me to do this post [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ryouready.wordpress.com&#038;blog=5891102&#038;post=690&#038;subd=ryouready&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p><a href="http://ryouready.files.wordpress.com/2011/04/pacman1.gif"><img class="alignleft size-full wp-image-695" title="pacman" src="http://ryouready.files.wordpress.com/2011/04/pacman1.gif?w=500" alt=""   /></a>The first week of April I attended an excellent workshop on <a href="http://en.wikipedia.org/wiki/Biplot" target="_blank">biplots</a> held by<a title="Michael Greenacre" href="http://www.econ.upf.edu/%7Emichael/"> Michael Greenacre</a> and <a href="http://www.statoek.wiso.uni-goettingen.de/cms/user/index.php?lang=de&amp;section=institut.team.onenadic">Oleg Nenadić</a> at the <a href="http://www.gesis.org/en/institute/">Gesis Institute</a> in Cologne, Germany. Throughout his presentations, Michael used animations to visualize the concepts he was explaining. He also included  animations in some of his papers. This inspired me to do this post in which I will show how to use LaTex, R and Sweave to include animations in a PDF document. Here is the <a title="Animations in PDF" href="http://ryouready.files.wordpress.com/2011/04/2011_animated_pdf_v1.pdf">PDF document</a> we will create (on MacOS the standard PDF viewer may not be able to play the animations, but Adobe Reader will). For this post some basic knowledge about Sweave is assumed.<span id="more-690"></span></p>
<p>First, let&#8217;s create a simple animation in R. I will use a neat  example Oleg used during the biplot workshop: Pacman eating. Herefore we need a pacman. We use a pie chart to construct him</p>
<pre style="color:#000000;background-color:#e9e9e9;font-size:9pt;font-family:Courier;"><span style="color:#000000;">pie</span><span style="color:#000000;">(</span><span style="color:#000000;">c</span><span style="color:#000000;">(</span><span style="color:#000000;">.1</span><span style="color:#000000;">,</span> <span style="color:#000000;">.9</span><span style="color:#000000;">,</span> <span style="color:#000000;">.1</span><span style="color:#000000;">)</span>                       <span style="color:#2f9956;"># a pie chart</span>
<span style="color:#000000;">pie</span><span style="color:#000000;">(</span><span style="color:#000000;">c</span><span style="color:#000000;">(</span><span style="color:#000000;">.1</span><span style="color:#000000;">,</span> <span style="color:#000000;">.9</span><span style="color:#000000;">,</span> <span style="color:#000000;">.1</span><span style="color:#000000;">),</span>                      <span style="color:#2f9956;"># a pie chart </span>
    col<span style="color:#000000;">=</span><span style="color:#000000;">c</span><span style="color:#000000;">(</span><span style="color:#0000ff;">"white"</span><span style="color:#000000;">,</span> <span style="color:#0000ff;">"yellow"</span><span style="color:#000000;">,</span> <span style="color:#0000ff;">"white"</span><span style="color:#000000;">),</span>  <span style="color:#2f9956;"># resembling pac man</span>
    border<span style="color:#000000;">=</span><span style="color:#7f0055;font-weight:bold;">NA</span><span style="color:#000000;">,</span> labels<span style="color:#000000;">=</span><span style="color:#7f0055;font-weight:bold;">NA</span><span style="color:#000000;">)</span>
<span style="color:#000000;">points</span><span style="color:#000000;">(</span><span style="color:#000000;">.3</span><span style="color:#000000;">,</span><span style="color:#000000;">.4</span><span style="color:#000000;">,</span> pch<span style="color:#000000;">=</span><span style="color:#000000;">16</span><span style="color:#000000;">,</span> cex<span style="color:#000000;">=</span><span style="color:#000000;">4)</span>            <span style="color:#2f9956;"># adding an eye</span></pre>
<p>Next, we will produce a series of pictures of Pacman by varying a parameter that specifies how far he opens his  mouth. Here, all the single pics are saved in one PDF file, each as one page.</p>
<pre style="color:#000000;background-color:#e9e9e9;font-size:9pt;font-family:Courier;">p <span style="color:#000000;">&lt;-</span> <span style="color:#000000;">seq</span><span style="color:#000000;">(</span><span style="color:#000000;">0.999</span><span style="color:#000000;">,</span> <span style="color:#000000;">.9</span><span style="color:#000000;">,</span> len<span style="color:#000000;">=</span><span style="color:#000000;">10</span><span style="color:#000000;">)</span>       <span style="color:#2f9956;"># parameters for opening mouth </span>
p <span style="color:#000000;">&lt;-</span> <span style="color:#000000;">c</span><span style="color:#000000;">(</span><span style="color:#000000;">rev</span><span style="color:#000000;">(</span>p<span style="color:#000000;">),</span> p<span style="color:#000000;">)</span>                 <span style="color:#2f9956;"># add reversed parameters</span>
<span style="color:#000000;">pdf</span><span style="color:#000000;">(</span>file<span style="color:#000000;">=</span><span style="color:#0000ff;">"pacman.pdf"</span><span style="color:#000000;">)</span>            <span style="color:#2f9956;"># open pdf device</span>
<span style="color:#7f0055;font-weight:bold;">for</span> <span style="color:#000000;">(</span>i <span style="color:#7f0055;font-weight:bold;">in</span> <span style="color:#000000;">1</span><span style="color:#000000;">:</span><span style="color:#000000;">length</span><span style="color:#000000;">(</span>p<span style="color:#000000;">)){</span>
  <span style="color:#000000;">pie</span><span style="color:#000000;">(</span><span style="color:#000000;">c</span><span style="color:#000000;">(</span><span style="color:#000000;">1</span><span style="color:#000000;">-</span>p<span style="color:#000000;">[</span>i<span style="color:#000000;">],</span> p<span style="color:#000000;">[</span>i<span style="color:#000000;">],</span> <span style="color:#000000;">1</span><span style="color:#000000;">-</span>p<span style="color:#000000;">[</span>i<span style="color:#000000;">]),</span>    <span style="color:#2f9956;"># pac man like pie chart</span>
      col<span style="color:#000000;">=</span><span style="color:#000000;">c</span><span style="color:#000000;">(</span><span style="color:#0000ff;">"white"</span><span style="color:#000000;">,</span> <span style="color:#0000ff;">"yellow"</span><span style="color:#000000;">,</span> <span style="color:#0000ff;">"white"</span><span style="color:#000000;">),</span>
      border<span style="color:#000000;">=</span><span style="color:#7f0055;font-weight:bold;">NA</span><span style="color:#000000;">,</span> labels<span style="color:#000000;">=</span><span style="color:#7f0055;font-weight:bold;">NA</span><span style="color:#000000;">)</span>
  <span style="color:#000000;">points</span><span style="color:#000000;">(</span><span style="color:#000000;">.3</span><span style="color:#000000;">,</span><span style="color:#000000;">.4</span><span style="color:#000000;">,</span> pch<span style="color:#000000;">=</span><span style="color:#000000;">16</span><span style="color:#000000;">,</span> cex<span style="color:#000000;">=4</span><span style="color:#000000;">)</span>    <span style="color:#2f9956;"># add the eye</span>
<span style="color:#000000;">}</span>
dev<span style="color:#000000;">.</span><span style="color:#000000;">off</span><span style="color:#000000;">()</span>                         <span style="color:#2f9956;"># close pdf device</span></pre>
<p>Now, each page of the PDF file contains a single frame of an animation. To include it as an  animation in LaTex the <tt>animate</tt> package can be used. Here is the whole code with the Pacman frames being rendered and included via LaTex.</p>
<pre style="color:#000000;background-color:#e9e9e9;font-size:9pt;font-family:Courier;">\documentclass<span style="color:#000000;">{</span>article<span style="color:#000000;">}</span>
\usepackage<span style="color:#000000;">{</span>animate<span style="color:#000000;">} %</span> <span style="color:#7f0055;font-weight:bold;">for</span> animated figures

<span style="color:#0000ff;">\t</span>itle<span style="color:#000000;">{</span>Animations <span style="color:#7f0055;font-weight:bold;">in</span> \LaTeX<span style="color:#000000;">{}</span> via <span style="color:#000000;">{</span>\sf R<span style="color:#000000;">}</span> and Sweave<span style="color:#000000;">}</span>
<span style="color:#0000ff;">\a</span>uthor<span style="color:#000000;">{</span>Mark Heckmann<span style="color:#000000;">}</span>

<span style="color:#0000ff;">\b</span>egin<span style="color:#000000;">{</span>document<span style="color:#000000;">}</span>
\maketitle

<span style="color:#000000;">&lt;&lt;</span>echo<span style="color:#000000;">=</span>false<span style="color:#000000;">,</span> results<span style="color:#000000;">=</span>hide<span style="color:#000000;">&gt;&gt;=</span>
p <span style="color:#000000;">&lt;-</span> <span style="color:#000000;">seq</span><span style="color:#000000;">(</span><span style="color:#000000;">0.999</span><span style="color:#000000;">,</span> <span style="color:#000000;">.9</span><span style="color:#000000;">,</span> len<span style="color:#000000;">=</span><span style="color:#000000;">10</span><span style="color:#000000;">)</span>       <span style="color:#2f9956;"># parameters for opening mouth </span>
p <span style="color:#000000;">&lt;-</span> <span style="color:#000000;">c</span><span style="color:#000000;">(</span><span style="color:#000000;">rev</span><span style="color:#000000;">(</span>p<span style="color:#000000;">),</span> p<span style="color:#000000;">)</span>                 <span style="color:#2f9956;"># add reversed parameters</span>
<span style="color:#000000;">pdf</span><span style="color:#000000;">(</span>file<span style="color:#000000;">=</span><span style="color:#0000ff;">"pacman.pdf"</span><span style="color:#000000;">)</span>            <span style="color:#2f9956;"># open pdf device</span>
<span style="color:#7f0055;font-weight:bold;">for</span> <span style="color:#000000;">(</span>i <span style="color:#7f0055;font-weight:bold;">in</span> <span style="color:#000000;">1</span><span style="color:#000000;">:</span><span style="color:#000000;">length</span><span style="color:#000000;">(</span>p<span style="color:#000000;">)){</span>
  <span style="color:#000000;">pie</span><span style="color:#000000;">(</span><span style="color:#000000;">c</span><span style="color:#000000;">(</span><span style="color:#000000;">1</span><span style="color:#000000;">-</span>p<span style="color:#000000;">[</span>i<span style="color:#000000;">],</span> p<span style="color:#000000;">[</span>i<span style="color:#000000;">],</span> <span style="color:#000000;">1</span><span style="color:#000000;">-</span>p<span style="color:#000000;">[</span>i<span style="color:#000000;">]),</span>    <span style="color:#2f9956;"># pac man like pie chart</span>
      col<span style="color:#000000;">=</span><span style="color:#000000;">c</span><span style="color:#000000;">(</span><span style="color:#0000ff;">"white"</span><span style="color:#000000;">,</span> <span style="color:#0000ff;">"yellow"</span><span style="color:#000000;">,</span> <span style="color:#0000ff;">"white"</span><span style="color:#000000;">),</span>
      border<span style="color:#000000;">=</span><span style="color:#7f0055;font-weight:bold;">NA</span><span style="color:#000000;">,</span> labels<span style="color:#000000;">=</span><span style="color:#7f0055;font-weight:bold;">NA</span><span style="color:#000000;">)</span>
  <span style="color:#000000;">points</span><span style="color:#000000;">(</span><span style="color:#000000;">.3</span><span style="color:#000000;">,</span><span style="color:#000000;">.4</span><span style="color:#000000;">,</span> pch<span style="color:#000000;">=</span><span style="color:#000000;">16</span><span style="color:#000000;">,</span> cex<span style="color:#000000;">=</span><span style="color:#000000;">4</span><span style="color:#000000;">)</span>    <span style="color:#2f9956;"># add the eye</span>
<span style="color:#000000;">}</span>
dev<span style="color:#000000;">.</span><span style="color:#000000;">off</span><span style="color:#000000;">()</span>                         <span style="color:#2f9956;"># close pdf device</span>
<span style="color:#000000;">4</span>

<span style="color:#0000ff;">\b</span>egin<span style="color:#000000;">{</span>center<span style="color:#000000;">}</span>
<span style="color:#0000ff;">\a</span>nimategraphics<span style="color:#000000;">[</span>loop<span style="color:#000000;">,</span> width<span style="color:#000000;">=</span><span style="color:#000000;">.7</span>\linewidth<span style="color:#000000;">]{</span><span style="color:#000000;">12</span><span style="color:#000000;">}{</span>pacman<span style="color:#000000;">}{}{}</span><span style="color:#0000ff;">\\</span>
<span style="color:#0000ff;">\v</span>space<span style="color:#000000;">{-</span><span style="color:#000000;">5</span>mm<span style="color:#000000;">}</span> Click me<span style="color:#000000;">!</span>
\end<span style="color:#000000;">{</span>center<span style="color:#000000;">}</span>
\end<span style="color:#000000;">{</span>document<span style="color:#000000;">}</span></pre>
<p>If you click on Pacman in the PDF file, he will start eating. Now let&#8217;s create another example and add a panel to control the  animation in the PDF. To add controls to the animation use the controls tag in the <tt>\animategraphics</tt> command. In the example several values from a uniform  distribution are sampled and their mean is calculated. The mean values are plotted in a histogram. The example is supposed to demonstrate the central limit theorem.</p>
<pre style="color:#000000;background-color:#e9e9e9;font-size:9pt;font-family:Courier;"><span style="color:#000000;">&lt;&lt;</span>eval<span style="color:#000000;">=</span>true<span style="color:#000000;">,</span> echo<span style="color:#000000;">=</span>false<span style="color:#000000;">,</span> results<span style="color:#000000;">=</span>hide<span style="color:#000000;">&gt;&gt;=</span>
<span style="color:#000000;">pdf</span><span style="color:#000000;">(</span><span style="color:#0000ff;">"limit.pdf"</span><span style="color:#000000;">)</span>                            <span style="color:#2f9956;"># open pdf device</span>
msam <span style="color:#000000;">&lt;-</span> <span style="color:#7f0055;font-weight:bold;">NA</span>                                  <span style="color:#2f9956;"># set up empty vector</span>
ns <span style="color:#000000;">&lt;-</span> <span style="color:#000000;">3</span>                                     <span style="color:#2f9956;"># sample size</span>
<span style="color:#7f0055;font-weight:bold;">for</span><span style="color:#000000;">(</span>i <span style="color:#7f0055;font-weight:bold;">in</span> <span style="color:#000000;">1</span><span style="color:#000000;">:</span><span style="color:#000000;">500</span><span style="color:#000000;">){</span>
  sam <span style="color:#000000;">&lt;-</span> <span style="color:#000000;">runif</span><span style="color:#000000;">(</span>ns<span style="color:#000000;">) *</span> <span style="color:#000000;">10</span>                     <span style="color:#2f9956;"># draw sample</span>
  msam<span style="color:#000000;">[</span>i<span style="color:#000000;">] &lt;-</span> <span style="color:#000000;">mean</span><span style="color:#000000;">(</span>sam<span style="color:#000000;">)</span>                      <span style="color:#2f9956;"># save mean of sample</span>
  h <span style="color:#000000;">&lt;-</span> <span style="color:#000000;">hist</span><span style="color:#000000;">(</span>msam<span style="color:#000000;">,</span> breaks<span style="color:#000000;">=</span><span style="color:#000000;">seq</span><span style="color:#000000;">(</span><span style="color:#000000;">0</span><span style="color:#000000;">,</span><span style="color:#000000;">10</span><span style="color:#000000;">,</span> len<span style="color:#000000;">=</span><span style="color:#000000;">50</span><span style="color:#000000;">),</span> <span style="color:#2f9956;"># histogram of all means</span>
            xlim<span style="color:#000000;">=</span><span style="color:#000000;">c</span><span style="color:#000000;">(</span><span style="color:#000000;">0</span><span style="color:#000000;">,</span><span style="color:#000000;">10</span><span style="color:#000000;">),</span> col<span style="color:#000000;">=</span><span style="color:#000000;">grey</span><span style="color:#000000;">(</span><span style="color:#000000;">.9</span><span style="color:#000000;">),</span>
            xlab<span style="color:#000000;">=</span><span style="color:#0000ff;">""</span><span style="color:#000000;">,</span> main<span style="color:#000000;">=</span><span style="color:#0000ff;">""</span><span style="color:#000000;">,</span> border<span style="color:#000000;">=</span><span style="color:#0000ff;">"white"</span><span style="color:#000000;">,</span> las<span style="color:#000000;">=</span><span style="color:#000000;">1</span><span style="color:#000000;">)</span>
  <span style="color:#000000;">points</span><span style="color:#000000;">(</span>sam<span style="color:#000000;">,</span> <span style="color:#000000;">rep</span><span style="color:#000000;">(</span><span style="color:#000000;">max</span><span style="color:#000000;">(</span>h$count<span style="color:#000000;">),</span> <span style="color:#000000;">length</span><span style="color:#000000;">(</span>sam<span style="color:#000000;">)),</span>
         pch<span style="color:#000000;">=</span><span style="color:#000000;">16</span><span style="color:#000000;">,</span> col<span style="color:#000000;">=</span><span style="color:#000000;">grey</span><span style="color:#000000;">(</span><span style="color:#000000;">.2</span><span style="color:#000000;">))</span>              <span style="color:#2f9956;"># add sampled values</span>
  <span style="color:#000000;">points</span><span style="color:#000000;">(</span>msam<span style="color:#000000;">[</span>i<span style="color:#000000;">],</span> <span style="color:#000000;">max</span><span style="color:#000000;">(</span>h$count<span style="color:#000000;">),</span>             <span style="color:#2f9956;"># add sample mean value</span>
         col<span style="color:#000000;">=</span><span style="color:#0000ff;">"red"</span><span style="color:#000000;">,</span> pch<span style="color:#000000;">=</span><span style="color:#000000;">15</span><span style="color:#000000;">)</span>
  <span style="color:#000000;">text</span><span style="color:#000000;">(</span><span style="color:#000000;">10</span><span style="color:#000000;">,</span> <span style="color:#000000;">max</span><span style="color:#000000;">(</span>h$count<span style="color:#000000;">),</span> <span style="color:#000000;">paste</span><span style="color:#000000;">(</span><span style="color:#0000ff;">"sample no"</span><span style="color:#000000;">,</span> i<span style="color:#000000;">))</span>
  <span style="color:#000000;">hist</span><span style="color:#000000;">(</span>msam<span style="color:#000000;">[</span>i<span style="color:#000000;">],</span> breaks<span style="color:#000000;">=</span><span style="color:#000000;">seq</span><span style="color:#000000;">(</span><span style="color:#000000;">0</span><span style="color:#000000;">,</span><span style="color:#000000;">10</span><span style="color:#000000;">,</span> len<span style="color:#000000;">=</span><span style="color:#000000;">50</span><span style="color:#000000;">),</span>   <span style="color:#2f9956;"># ovelay sample mean </span>
       xlim<span style="color:#000000;">=</span><span style="color:#000000;">c</span><span style="color:#000000;">(</span><span style="color:#000000;">0</span><span style="color:#000000;">,</span><span style="color:#000000;">10</span><span style="color:#000000;">),</span> col<span style="color:#000000;">=</span><span style="color:#0000ff;">"red"</span><span style="color:#000000;">,</span> add<span style="color:#000000;">=</span><span style="color:#7f0055;font-weight:bold;">T</span><span style="color:#000000;">,</span>      <span style="color:#2f9956;"># in histogram</span>
       xlab<span style="color:#000000;">=</span><span style="color:#0000ff;">""</span><span style="color:#000000;">,</span> border<span style="color:#000000;">=</span><span style="color:#0000ff;">"white"</span><span style="color:#000000;">,</span> las<span style="color:#000000;">=</span><span style="color:#000000;">1</span><span style="color:#000000;">)</span>
<span style="color:#000000;">}</span>
dev<span style="color:#000000;">.</span><span style="color:#000000;">off</span><span style="color:#000000;">()</span>                                   <span style="color:#2f9956;"># close pdf device</span>
<span style="color:#000000;">4</span></pre>
<p>As a last example we will include a 3D animation created using <tt>rgl</tt>. Herefore we will create random points and rotate them about the x-axis and then about the y-axis.</p>
<pre style="color:#000000;background-color:#e9e9e9;font-size:9pt;font-family:Courier;"><span style="color:#000000;">&lt;&lt;</span>echo<span style="color:#000000;">=</span>f<span style="color:#000000;">,</span> results<span style="color:#000000;">=</span>hide<span style="color:#000000;">&gt;&gt;=</span>
<span style="color:#000000;">library</span><span style="color:#000000;">(</span>rgl<span style="color:#000000;">)</span>                          <span style="color:#2f9956;"># load rgl library</span>
x <span style="color:#000000;">&lt;-</span> <span style="color:#000000;">matrix</span><span style="color:#000000;">(</span><span style="color:#000000;">rnorm</span><span style="color:#000000;">(</span><span style="color:#000000;">30</span><span style="color:#000000;">),</span> ncol<span style="color:#000000;">=</span><span style="color:#000000;">3</span><span style="color:#000000;">)</span>        <span style="color:#2f9956;"># make random points </span>
<span style="color:#000000;">plot3d</span><span style="color:#000000;">(</span>x<span style="color:#000000;">)</span>                             <span style="color:#2f9956;"># plot points in 3d device</span>
<span style="color:#000000;">par3d</span><span style="color:#000000;">(</span>params<span style="color:#000000;">=</span><span style="color:#000000;">list</span><span style="color:#000000;">(</span>
      windowRect<span style="color:#000000;">=</span><span style="color:#000000;">c</span><span style="color:#000000;">(</span><span style="color:#000000;">100</span><span style="color:#000000;">,</span><span style="color:#000000;">100</span><span style="color:#000000;">,</span><span style="color:#000000;">600</span><span style="color:#000000;">,</span><span style="color:#000000;">600</span><span style="color:#000000;">)))</span> <span style="color:#2f9956;"># enlarge 3d device</span>
<span style="color:#000000;">view3d</span><span style="color:#000000;">(</span> theta <span style="color:#000000;">=</span> <span style="color:#000000;">0</span><span style="color:#000000;">,</span> phi <span style="color:#000000;">=</span> <span style="color:#000000;">0</span><span style="color:#000000;">)</span>           <span style="color:#2f9956;"># change 3d view angle</span>
M <span style="color:#000000;">&lt;-</span> <span style="color:#000000;">par3d</span><span style="color:#000000;">(</span><span style="color:#0000ff;">"userMatrix"</span><span style="color:#000000;">)</span>              <span style="color:#2f9956;"># get current position matrix</span>
M1 <span style="color:#000000;">&lt;-</span> <span style="color:#000000;">rotate3d</span><span style="color:#000000;">(</span>M<span style="color:#000000;">,</span> <span style="color:#000000;">.9</span><span style="color:#000000;">*</span>pi<span style="color:#000000;">/</span><span style="color:#000000;">2</span><span style="color:#000000;">,</span> <span style="color:#000000;">1</span><span style="color:#000000;">,</span> <span style="color:#000000;">0</span><span style="color:#000000;">,</span> <span style="color:#000000;">0</span><span style="color:#000000;">)</span>
M2 <span style="color:#000000;">&lt;-</span> <span style="color:#000000;">rotate3d</span><span style="color:#000000;">(</span>M1<span style="color:#000000;">,</span> pi<span style="color:#000000;">/</span><span style="color:#000000;">2</span><span style="color:#000000;">,</span> <span style="color:#000000;">0</span><span style="color:#000000;">,</span> <span style="color:#000000;">0</span><span style="color:#000000;">,</span> <span style="color:#000000;">1</span><span style="color:#000000;">)</span>
<span style="color:#000000;">movie3d</span><span style="color:#000000;">(</span><span style="color:#000000;">par3dinterp</span><span style="color:#000000;">(</span> userMatrix<span style="color:#000000;">=</span><span style="color:#000000;">list</span><span style="color:#000000;">(</span>M<span style="color:#000000;">,</span> M1<span style="color:#000000;">,</span> M2<span style="color:#000000;">,</span> M1<span style="color:#000000;">,</span> M<span style="color:#000000;">),</span>
        method<span style="color:#000000;">=</span><span style="color:#0000ff;">"linear"</span><span style="color:#000000;">),</span> duration<span style="color:#000000;">=</span><span style="color:#000000;">4</span><span style="color:#000000;">,</span> convert<span style="color:#000000;">=</span><span style="color:#7f0055;font-weight:bold;">F</span><span style="color:#000000;">,</span>
        clean<span style="color:#000000;">=</span><span style="color:#7f0055;font-weight:bold;">F</span><span style="color:#000000;">,</span> dir<span style="color:#000000;">=</span><span style="color:#0000ff;">"pics"</span><span style="color:#000000;">)</span>          <span style="color:#2f9956;"># save frames in pics folder</span>
<span style="color:#000000;">4</span></pre>
<p>The inclusion into LaTex works a bit different this time. This time we do not include the single pages from a PDF as frames but we use singe .png pics that have been geberetaed by <tt>movid3d()</tt>. The default file name for the frames generated by movie3d is &#8220;movie&#8221; plus the frame number.</p>
<pre style="color:#000000;background-color:#e9e9e9;font-size:9pt;font-family:Courier;"><span style="color:#0000ff;">\b</span>egin<span style="color:#000000;">{</span>center<span style="color:#000000;">}</span>
<span style="color:#0000ff;">\a</span>nimategraphics<span style="color:#000000;">[</span>controls<span style="color:#000000;">,</span> loop<span style="color:#000000;">,</span> width<span style="color:#000000;">=</span><span style="color:#000000;">.7</span>\linewidth<span style="color:#000000;">]{</span><span style="color:#000000;">6</span><span style="color:#000000;">}</span>
  <span style="color:#000000;">{</span>pics<span style="color:#000000;">/</span>movie<span style="color:#000000;">}{</span><span style="color:#000000;">001</span><span style="color:#000000;">}{</span><span style="color:#000000;">040</span><span style="color:#000000;">}</span>
\end<span style="color:#000000;">{</span>center<span style="color:#000000;">}</span></pre>
<p>Here is the <a href="http://ryouready.files.wordpress.com/2011/04/2011_animated_pdf_v1_code.pdf">whole code</a> for the <a href="http://ryouready.files.wordpress.com/2011/04/2011_animated_pdf_v1.pdf">PDF</a> containing the three animations ready to be Sweaved (make sure to set the directory in the last animation correctly).</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/ryouready.wordpress.com/690/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/ryouready.wordpress.com/690/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ryouready.wordpress.com&#038;blog=5891102&#038;post=690&#038;subd=ryouready&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://ryouready.wordpress.com/2011/04/18/using-r-sweave-and-latex-to-integrate-animations-into-pdfs/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
	
		<media:content url="http://2.gravatar.com/avatar/80731da9aeab670f39dfa6f74a306222?s=96&#38;d=http%3A%2F%2F2.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96" medium="image">
			<media:title type="html">markheckmann</media:title>
		</media:content>

		<media:content url="http://ryouready.files.wordpress.com/2011/04/pacman1.gif" medium="image">
			<media:title type="html">pacman</media:title>
		</media:content>
	</item>
		<item>
		<title>Animate .gif images in R / ImageMagick</title>
		<link>http://ryouready.wordpress.com/2010/11/21/animate-gif-images-in-r-imagemagick/</link>
		<comments>http://ryouready.wordpress.com/2010/11/21/animate-gif-images-in-r-imagemagick/#comments</comments>
		<pubDate>Sun, 21 Nov 2010 13:48:37 +0000</pubDate>
		<dc:creator>markheckmann</dc:creator>
				<category><![CDATA[R / R-Code]]></category>

		<guid isPermaLink="false">http://ryouready.wordpress.com/?p=618</guid>
		<description><![CDATA[Yesterday I surfed the web looking for 3D wireframe examples to explain linear models in class. I stumbled across this site where animated 3D wireframe plots are outputted by SAS.  Below I did something similar in R. This post shows the few steps of how to create an animated .gif file using R and ImageMagick. [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ryouready.wordpress.com&#038;blog=5891102&#038;post=618&#038;subd=ryouready&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p><a href="http://ryouready.files.wordpress.com/2010/11/example_corner.gif"><img class="alignleft size-full wp-image-670" style="margin:7px;" title="example_corner" src="http://ryouready.files.wordpress.com/2010/11/example_corner.gif?w=500" alt=""   /></a>Yesterday I surfed the web looking for 3D wireframe examples to explain linear models in class. I stumbled across this site where <a href="http://www.ats.ucla.edu/stat/sas/examples/aw/example_graphs.htm">animated 3D wireframe plots</a> are outputted by SAS.  Below I did something similar in R. This post shows the few steps of how to create an animated .gif file using R and ImageMagick. Here I assume that you have <a href="http://www.imagemagick.org/">ImageMagick</a> installed on your computer. As far as I know it is also possible to produce animated .gif files using R only, e.g. with <tt>write.gif()</tt> from the <a href="http://cran.r-project.org/web/packages/caTools/index.html"><tt>caTools</tt></a> package. But using ImageMagick is straighforward, gives you control over the conversion and .gif production and is the free standard program for conversion.<span id="more-618"></span></p>
<p>First a simple countdown example. To be sure not to overwrite anything I will create a new folder and set the working directory to the new folder﻿.</p>
<pre style="color:#000000;background-color:#e9e9e9;font-size:9pt;font-family:Courier;">dir<span style="color:#000000;">.</span><span style="color:#000000;">create</span><span style="color:#000000;">(</span><span style="color:#0000ff;">"examples"</span><span style="color:#000000;">)</span>
<span style="color:#000000;">setwd</span><span style="color:#000000;">(</span><span style="color:#0000ff;">"examples"</span><span style="color:#000000;">)</span>

<span style="color:#2f9956;"># example 1: simple animated countdown from 10 to "GO!".</span>
<span style="color:#000000;">png</span><span style="color:#000000;">(</span>file<span style="color:#000000;">=</span><span style="color:#0000ff;">"example%02d.png"</span><span style="color:#000000;">,</span> width<span style="color:#000000;">=</span><span style="color:#000000;">200</span><span style="color:#000000;">,</span> height<span style="color:#000000;">=</span><span style="color:#000000;">200</span><span style="color:#000000;">)</span>
  <span style="color:#7f0055;font-weight:bold;">for</span> <span style="color:#000000;">(</span>i <span style="color:#7f0055;font-weight:bold;">in</span> <span style="color:#000000;">c</span><span style="color:#000000;">(</span><span style="color:#000000;">10</span><span style="color:#000000;">:</span><span style="color:#000000;">1</span><span style="color:#000000;">,</span> <span style="color:#0000ff;">"G0!"</span><span style="color:#000000;">)){</span>
    plot<span style="color:#000000;">.</span><span style="color:#000000;">new</span><span style="color:#000000;">()</span>
    <span style="color:#000000;">text</span><span style="color:#000000;">(</span><span style="color:#000000;">.5</span><span style="color:#000000;">,</span> <span style="color:#000000;">.5</span><span style="color:#000000;">,</span> i<span style="color:#000000;">,</span> cex <span style="color:#000000;">=</span> <span style="color:#000000;">6</span><span style="color:#000000;">)</span>
  <span style="color:#000000;">}</span>
dev<span style="color:#000000;">.</span><span style="color:#000000;">off</span><span style="color:#000000;">()</span>

<span style="color:#2f9956;"># convert the .png files to one .gif file using ImageMagick. </span>
<span style="color:#2f9956;"># The system() function executes the command as if it was done</span>
<span style="color:#2f9956;"># in the terminal. the -delay flag sets the time between showing</span>
<span style="color:#2f9956;"># the frames, i.e. the speed of the animation.</span>
<span style="color:#000000;">system</span><span style="color:#000000;">(</span><span style="color:#0000ff;">"convert -delay 80 *.png example_1.gif"</span><span style="color:#000000;">)</span>

<span style="color:#2f9956;"># to not leave the directory with the single jpeg files</span>
<span style="color:#2f9956;"># I remove them.</span>
file<span style="color:#000000;">.</span><span style="color:#000000;">remove</span><span style="color:#000000;">(</span>list<span style="color:#000000;">.</span><span style="color:#000000;">files</span><span style="color:#000000;">(</span>pattern<span style="color:#000000;">=</span><span style="color:#0000ff;">".png"</span><span style="color:#000000;">))</span></pre>
<p style="text-align:center;"><a href="http://ryouready.files.wordpress.com/2010/11/example_1a1.gif"></a><a href="http://ryouready.files.wordpress.com/2010/11/example_1a2.gif"><img class="aligncenter size-full wp-image-667" style="border:0 none;" title="example_1a" src="http://ryouready.files.wordpress.com/2010/11/example_1a2.gif?w=500" alt=""   /></a></p>
<p>Above a loop is used to do the plotting. A new .png file for each plot is created automatically. The <tt>"%02d"</tt> part in the  filenamepart is a placeholder here for a two character counter (01,02 etc.). So we do not have to hard-code the filename each time.</p>
<p>Now I want a linear model to be visualized as a 3d mesh.  A 3D surface can easily be plotted using the <tt>wireframe()</tt> function from the <tt>lattice</tt> package (or other functions available in R; also see the <tt>rgl</tt> package for rotatable 3D output).</p>
<pre style="color:#000000;background-color:#e9e9e9;font-size:9pt;font-family:Courier;"><span style="color:#000000;">library</span><span style="color:#000000;">(</span>lattice<span style="color:#000000;">)</span>
b0 <span style="color:#000000;">&lt;-</span> <span style="color:#000000;">10</span>
b1 <span style="color:#000000;">&lt;-</span> <span style="color:#000000;">.5</span>
b2 <span style="color:#000000;">&lt;-</span> <span style="color:#000000;">.3</span>
g <span style="color:#000000;">&lt;-</span> expand<span style="color:#000000;">.</span><span style="color:#000000;">grid</span><span style="color:#000000;">(</span>x <span style="color:#000000;">=</span> <span style="color:#000000;">1</span><span style="color:#000000;">:</span><span style="color:#000000;">20</span><span style="color:#000000;">,</span> y <span style="color:#000000;">=</span> <span style="color:#000000;">1</span><span style="color:#000000;">:</span><span style="color:#000000;">20</span><span style="color:#000000;">)</span>
g$z <span style="color:#000000;">&lt;-</span> b0 <span style="color:#000000;">+</span> b1<span style="color:#000000;">*</span>g$x <span style="color:#000000;">+</span> b2<span style="color:#000000;">*</span>g$y
<span style="color:#000000;">wireframe</span><span style="color:#000000;">(</span>z <span style="color:#000000;">~</span> x <span style="color:#000000;">*</span> y<span style="color:#000000;">,</span> data <span style="color:#000000;">=</span> g<span style="color:#000000;">)</span>

<span style="color:#2f9956;"># to rotate the plot</span>
<span style="color:#000000;">wireframe</span><span style="color:#000000;">(</span>z <span style="color:#000000;">~</span> x <span style="color:#000000;">*</span> y<span style="color:#000000;">,</span> data <span style="color:#000000;">=</span> g<span style="color:#000000;">,</span>
          screen <span style="color:#000000;">=</span> <span style="color:#000000;">list</span><span style="color:#000000;">(</span>z <span style="color:#000000;">=</span> <span style="color:#000000;">10</span><span style="color:#000000;">,</span> x <span style="color:#000000;">= -</span><span style="color:#000000;">60</span><span style="color:#000000;">))</span></pre>
<p>Now let&#8217;s create multiple files while changing the rotation angle. Note that <tt>wireframe()</tt> returns a trellis object which needs to be printed explicitly here using <tt>print()</tt>. As the code below produces over 150 images and merges them into one .gif file note that this may take a minute or two.</p>
<pre style="color:#000000;background-color:#e9e9e9;font-size:9pt;font-family:Courier;"><span style="color:#2f9956;"># example 2</span>
<span style="color:#000000;">png</span><span style="color:#000000;">(</span>file<span style="color:#000000;">=</span><span style="color:#0000ff;">"example%03d.png"</span><span style="color:#000000;">,</span> width<span style="color:#000000;">=</span><span style="color:#000000;">300</span><span style="color:#000000;">,</span> heigh<span style="color:#000000;">=</span><span style="color:#000000;">300</span><span style="color:#000000;">)</span>
  <span style="color:#7f0055;font-weight:bold;">for</span> <span style="color:#000000;">(</span>i <span style="color:#7f0055;font-weight:bold;">in</span> <span style="color:#000000;">seq</span><span style="color:#000000;">(</span><span style="color:#000000;">0</span><span style="color:#000000;">,</span> <span style="color:#000000;">350</span> <span style="color:#000000;">,</span> <span style="color:#000000;">10</span><span style="color:#000000;">)){</span>
    <span style="color:#000000;">print</span><span style="color:#000000;">(</span><span style="color:#000000;">wireframe</span><span style="color:#000000;">(</span>z <span style="color:#000000;">~</span> x <span style="color:#000000;">*</span> y<span style="color:#000000;">,</span> data <span style="color:#000000;">=</span> g<span style="color:#000000;">,</span>
              screen <span style="color:#000000;">=</span> <span style="color:#000000;">list</span><span style="color:#000000;">(</span>z <span style="color:#000000;">=</span> i<span style="color:#000000;">,</span> x <span style="color:#000000;">= -</span><span style="color:#000000;">60</span><span style="color:#000000;">)))</span>
  <span style="color:#000000;">}</span>
dev<span style="color:#000000;">.</span><span style="color:#000000;">off</span><span style="color:#000000;">()</span>
<span style="color:#2f9956;"># convert pngs to one gif using ImageMagick</span>
<span style="color:#000000;">system</span><span style="color:#000000;">(</span><span style="color:#0000ff;">"convert -delay 40 *.png example_2_reduced.gif"</span><span style="color:#000000;">)</span>

<span style="color:#2f9956;"># cleaning up</span>
file<span style="color:#000000;">.</span><span style="color:#000000;">remove</span><span style="color:#000000;">(</span>list<span style="color:#000000;">.</span><span style="color:#000000;">files</span><span style="color:#000000;">(</span>pattern<span style="color:#000000;">=</span><span style="color:#0000ff;">".png"</span><span style="color:#000000;">))</span></pre>
<p><!--HTML generated by highlight 3.1 beta2, http://www.andre-simon.de/--></p>
<p style="text-align:center;"><a href="http://ryouready.files.wordpress.com/2010/11/example_2_reduced.gif"><img class="aligncenter size-full wp-image-656" style="border:0 none;" title="example_2_reduced" src="http://ryouready.files.wordpress.com/2010/11/example_2_reduced.gif?w=500" alt=""   /></a></p>
<p>Now I want the same as above but for a model with an interaction and I want to make the plot a bit more pretty. This time I use .pdf as output file. This is just to demonstrate that other formats  than .png can be used. Note that the <tt>"%02d"</tt> part of the filename has disappeared as I only create one .pdf file with multiple pages, not multiple .pdf files.</p>
<pre style="color:#000000;background-color:#e9e9e9;font-size:9pt;font-family:Courier;"><span style="color:#2f9956;"># example 3</span>
b0 <span style="color:#000000;">&lt;-</span> <span style="color:#000000;">10</span>
b1 <span style="color:#000000;">&lt;-</span> <span style="color:#000000;">.5</span>
b2 <span style="color:#000000;">&lt;-</span> <span style="color:#000000;">.3</span>
int12 <span style="color:#000000;">&lt;-</span> <span style="color:#000000;">.2</span>
g <span style="color:#000000;">&lt;-</span> expand<span style="color:#000000;">.</span><span style="color:#000000;">grid</span><span style="color:#000000;">(</span>x <span style="color:#000000;">=</span> <span style="color:#000000;">1</span><span style="color:#000000;">:</span><span style="color:#000000;">20</span><span style="color:#000000;">,</span> y <span style="color:#000000;">=</span> <span style="color:#000000;">1</span><span style="color:#000000;">:</span><span style="color:#000000;">20</span><span style="color:#000000;">)</span>
g$z <span style="color:#000000;">&lt;-</span> b0 <span style="color:#000000;">+</span> b1<span style="color:#000000;">*</span>g$x <span style="color:#000000;">+</span> b2<span style="color:#000000;">*</span>g$y <span style="color:#000000;">+</span> int12<span style="color:#000000;">*</span>g$x<span style="color:#000000;">*</span>g$y

<span style="color:#000000;">pdf</span><span style="color:#000000;">(</span>file<span style="color:#000000;">=</span><span style="color:#0000ff;">"example_3.pdf"</span><span style="color:#000000;">,</span> width<span style="color:#000000;">=</span><span style="color:#000000;">4</span><span style="color:#000000;">,</span> height<span style="color:#000000;">=</span><span style="color:#000000;">4</span><span style="color:#000000;">)</span>
  <span style="color:#7f0055;font-weight:bold;">for</span> <span style="color:#000000;">(</span>i <span style="color:#7f0055;font-weight:bold;">in</span> <span style="color:#000000;">seq</span><span style="color:#000000;">(</span><span style="color:#000000;">0</span><span style="color:#000000;">,</span> <span style="color:#000000;">350</span> <span style="color:#000000;">,</span><span style="color:#000000;">10</span><span style="color:#000000;">)){</span>
    <span style="color:#000000;">print</span><span style="color:#000000;">(</span><span style="color:#000000;">wireframe</span><span style="color:#000000;">(</span>z <span style="color:#000000;">~</span> x <span style="color:#000000;">*</span> y<span style="color:#000000;">,</span> data <span style="color:#000000;">=</span> g<span style="color:#000000;">,</span>
              screen <span style="color:#000000;">=</span> <span style="color:#000000;">list</span><span style="color:#000000;">(</span>z <span style="color:#000000;">=</span> i<span style="color:#000000;">,</span> x <span style="color:#000000;">= -</span><span style="color:#000000;">60</span><span style="color:#000000;">),</span>
              drape<span style="color:#000000;">=</span><span style="color:#7f0055;font-weight:bold;">TRUE</span><span style="color:#000000;">))</span>
  <span style="color:#000000;">}</span>
dev<span style="color:#000000;">.</span><span style="color:#000000;">off</span><span style="color:#000000;">()</span>
<span style="color:#2f9956;"># convert pdf to gif using ImageMagick</span>
<span style="color:#000000;">system</span><span style="color:#000000;">(</span><span style="color:#0000ff;">"convert -delay 40 *.pdf example_3_reduced.gif"</span><span style="color:#000000;">)</span>
<span style="color:#2f9956;"># cleaning up</span>
file<span style="color:#000000;">.</span><span style="color:#000000;">remove</span><span style="color:#000000;">(</span>list<span style="color:#000000;">.</span><span style="color:#000000;">files</span><span style="color:#000000;">(</span>pattern<span style="color:#000000;">=</span><span style="color:#0000ff;">".pdf"</span><span style="color:#000000;">))</span></pre>
<p style="text-align:center;"><a href="http://ryouready.files.wordpress.com/2010/11/example_3_reduced.gif"><img class="aligncenter size-full wp-image-663" style="border:0 none;" title="example_3_reduced" src="http://ryouready.files.wordpress.com/2010/11/example_3_reduced.gif?w=500" alt=""   /></a></p>
<p>The last example is a visual comparison of the interaction and a non-interaction model. Here we now have the models on the same scale. Before I did not specify the scale limits.</p>
<pre style="color:#000000;background-color:#e9e9e9;font-size:9pt;font-family:Courier;"><span style="color:#2f9956;"># example 4</span>
b0 <span style="color:#000000;">&lt;-</span> <span style="color:#000000;">10</span>
b1 <span style="color:#000000;">&lt;-</span> <span style="color:#000000;">.5</span>
b2 <span style="color:#000000;">&lt;-</span> <span style="color:#000000;">.3</span>
int12 <span style="color:#000000;">&lt;-</span> <span style="color:#000000;">.2</span>
g <span style="color:#000000;">&lt;-</span> expand<span style="color:#000000;">.</span><span style="color:#000000;">grid</span><span style="color:#000000;">(</span>x <span style="color:#000000;">=</span> <span style="color:#000000;">1</span><span style="color:#000000;">:</span><span style="color:#000000;">20</span><span style="color:#000000;">,</span> y <span style="color:#000000;">=</span> <span style="color:#000000;">1</span><span style="color:#000000;">:</span><span style="color:#000000;">20</span><span style="color:#000000;">)</span>
z <span style="color:#000000;">&lt;-</span> <span style="color:#000000;">c</span><span style="color:#000000;">(</span> b0 <span style="color:#000000;">+</span> b1<span style="color:#000000;">*</span>g$x <span style="color:#000000;">+</span> b2<span style="color:#000000;">*</span>g$y<span style="color:#000000;">,</span>
        b0 <span style="color:#000000;">+</span> b1<span style="color:#000000;">*</span>g$x <span style="color:#000000;">+</span> b2<span style="color:#000000;">*</span>g$y <span style="color:#000000;">+</span> int12<span style="color:#000000;">*</span>g$x<span style="color:#000000;">*</span>g$y<span style="color:#000000;">)</span>
g <span style="color:#000000;">&lt;-</span><span style="color:#000000;">rbind</span><span style="color:#000000;">(</span>g<span style="color:#000000;">,</span> g<span style="color:#000000;">)</span>
g$z <span style="color:#000000;">&lt;-</span> z
g$group <span style="color:#000000;">&lt;-</span> <span style="color:#000000;">gl</span><span style="color:#000000;">(</span><span style="color:#000000;">2</span><span style="color:#000000;">,</span> <span style="color:#000000;">nrow</span><span style="color:#000000;">(</span>g<span style="color:#000000;">)/</span><span style="color:#000000;">2</span><span style="color:#000000;">,</span> labels<span style="color:#000000;">=</span><span style="color:#000000;">c</span><span style="color:#000000;">(</span><span style="color:#0000ff;">"interaction"</span><span style="color:#000000;">,</span> <span style="color:#0000ff;">"no interaction"</span><span style="color:#000000;">))</span>

<span style="color:#000000;">png</span><span style="color:#000000;">(</span>file<span style="color:#000000;">=</span><span style="color:#0000ff;">"example%03d.png"</span><span style="color:#000000;">,</span> width<span style="color:#000000;">=</span><span style="color:#000000;">300</span><span style="color:#000000;">,</span> height<span style="color:#000000;">=</span><span style="color:#000000;">300</span><span style="color:#000000;">)</span>
  <span style="color:#7f0055;font-weight:bold;">for</span> <span style="color:#000000;">(</span>i <span style="color:#7f0055;font-weight:bold;">in</span> <span style="color:#000000;">seq</span><span style="color:#000000;">(</span><span style="color:#000000;">0</span><span style="color:#000000;">,</span> <span style="color:#000000;">350</span> <span style="color:#000000;">,</span><span style="color:#000000;">10</span><span style="color:#000000;">)){</span>
    <span style="color:#000000;">print</span><span style="color:#000000;">(</span><span style="color:#000000;">wireframe</span><span style="color:#000000;">(</span>z <span style="color:#000000;">~</span> x <span style="color:#000000;">*</span> y<span style="color:#000000;">,</span> data <span style="color:#000000;">=</span> g<span style="color:#000000;">,</span> groups<span style="color:#000000;">=</span>group<span style="color:#000000;">,</span>
              screen <span style="color:#000000;">=</span> <span style="color:#000000;">list</span><span style="color:#000000;">(</span>z <span style="color:#000000;">=</span> i<span style="color:#000000;">,</span> x <span style="color:#000000;">= -</span><span style="color:#000000;">60</span><span style="color:#000000;">)))</span>
  <span style="color:#000000;">}</span>
dev<span style="color:#000000;">.</span><span style="color:#000000;">off</span><span style="color:#000000;">()</span>
<span style="color:#2f9956;"># convert pngs to one gif using ImageMagick</span>
<span style="color:#000000;">system</span><span style="color:#000000;">(</span><span style="color:#0000ff;">"convert -delay 40 *.png example_4.gif"</span><span style="color:#000000;">)</span>

<span style="color:#2f9956;"># cleaning up</span>
file<span style="color:#000000;">.</span><span style="color:#000000;">remove</span><span style="color:#000000;">(</span>list<span style="color:#000000;">.</span><span style="color:#000000;">files</span><span style="color:#000000;">(</span>pattern<span style="color:#000000;">=</span><span style="color:#0000ff;">".png"</span><span style="color:#000000;">))</span></pre>
<p style="text-align:center;"><a href="http://ryouready.files.wordpress.com/2010/11/example_4_reduced.gif"><img class="aligncenter size-full wp-image-664" style="border:0 none;" title="example_4_reduced" src="http://ryouready.files.wordpress.com/2010/11/example_4_reduced.gif?w=500" alt=""   /></a></p>
<p>Above I chose a small image size (300 x 300 pts). Smaller steps for rotation and a bigger picture size increases file sizes for examples 2, 3 and 4 to 3-5mb which is far too big for a web format. I am not familiar with image optimization and I suppose a smaller file sizes for the .gif file can easily be achieved by some optimization flags in ImageMagick. Any hints are welcome!</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/ryouready.wordpress.com/618/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/ryouready.wordpress.com/618/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ryouready.wordpress.com&#038;blog=5891102&#038;post=618&#038;subd=ryouready&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://ryouready.wordpress.com/2010/11/21/animate-gif-images-in-r-imagemagick/feed/</wfw:commentRss>
		<slash:comments>17</slash:comments>
	
		<media:content url="http://2.gravatar.com/avatar/80731da9aeab670f39dfa6f74a306222?s=96&#38;d=http%3A%2F%2F2.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96" medium="image">
			<media:title type="html">markheckmann</media:title>
		</media:content>

		<media:content url="http://ryouready.files.wordpress.com/2010/11/example_corner.gif" medium="image">
			<media:title type="html">example_corner</media:title>
		</media:content>

		<media:content url="http://ryouready.files.wordpress.com/2010/11/example_1a2.gif" medium="image">
			<media:title type="html">example_1a</media:title>
		</media:content>

		<media:content url="http://ryouready.files.wordpress.com/2010/11/example_2_reduced.gif" medium="image">
			<media:title type="html">example_2_reduced</media:title>
		</media:content>

		<media:content url="http://ryouready.files.wordpress.com/2010/11/example_3_reduced.gif" medium="image">
			<media:title type="html">example_3_reduced</media:title>
		</media:content>

		<media:content url="http://ryouready.files.wordpress.com/2010/11/example_4_reduced.gif" medium="image">
			<media:title type="html">example_4_reduced</media:title>
		</media:content>
	</item>
		<item>
		<title>Playing with the &#8216;playwith&#8217; package</title>
		<link>http://ryouready.wordpress.com/2010/03/23/playing-with-the-playwith-package/</link>
		<comments>http://ryouready.wordpress.com/2010/03/23/playing-with-the-playwith-package/#comments</comments>
		<pubDate>Tue, 23 Mar 2010 11:44:05 +0000</pubDate>
		<dc:creator>nattomi</dc:creator>
				<category><![CDATA[R / R-Code]]></category>
		<category><![CDATA[fields]]></category>
		<category><![CDATA[interactive plot]]></category>
		<category><![CDATA[playwith]]></category>
		<category><![CDATA[R.basic]]></category>
		<category><![CDATA[rggobi]]></category>

		<guid isPermaLink="false">http://ryouready.wordpress.com/?p=528</guid>
		<description><![CDATA[Abilities of R for creating graphics is great, but one thing I always missed is the possibility of creating interactive plots and being able to look at graphs while changing one ore more parameters. I know that there is rggobi, but so far I always ran into problems with flexibility each time I wanted to [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ryouready.wordpress.com&#038;blog=5891102&#038;post=528&#038;subd=ryouready&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p><a href="http://ryouready.files.wordpress.com/2010/03/playwith_demo.png"><img class="alignleft size-medium wp-image-552" style="margin:8px;" title="playwith_demo" src="http://ryouready.files.wordpress.com/2010/03/playwith_demo.png?w=240&#038;h=215" alt="" width="240" height="215" /></a>Abilities of R for creating graphics is great, but one thing I always missed is the possibility of creating interactive plots and being able to look at graphs while changing one ore more parameters. I know that there is <a href="http://www.ggobi.org/rggobi/">rggobi</a>, but so far I always ran into problems with flexibility each time I wanted to use it. So I kept on searching until I found <a href="http://code.google.com/p/playwith/">playwith</a> which is &#8220;an R package, providing a GTK+ graphical user interface for editing and interacting with R plots&#8221; as its homepage says. The homepage includes a lot of <a href="http://code.google.com/p/playwith/wiki/Screenshots">screenshots</a> with code snippets so this post doesn&#8217;t intend to give an extensive review about the possibilities of the playwith package to the reader. All I want to do now is present a small application of it.<span id="more-528"></span></p>
<p>I had some geospatial data I wanted to visualize. The data was a result of a computer simulation and consisted of a set of geographical coordinates and corresponding frequency values expressed in Hz. The values associated to the coordinates <img src='http://s0.wp.com/latex.php?latex=%28x%2Cy%29&amp;bg=ffffff&amp;fg=333333&amp;s=0' alt='(x,y)' title='(x,y)' class='latex' />  tells us the first eigenfrequency of the <a href="http://en.wikipedia.org/wiki/Schumann_resonances">Earth-ionosphere cavity</a> that would be measured at <a href="http://w.ggki.hu/index.php?id=38&amp;L=1">Nagycenk Observatory</a> in the case of an assumed lightning source at <img src='http://s0.wp.com/latex.php?latex=%28x%2Cy%29&amp;bg=ffffff&amp;fg=333333&amp;s=0' alt='(x,y)' title='(x,y)' class='latex' /> with certain properties.</p>
<p>At first, as always, we need to load some packages.<br />
<code><br />
library(R.basic) # for creating perspective plot<br />
library(playwith) # for creating interactive plot<br />
library(fields) # for plotting a map of the world</code></p>
<p>Then, we read in our data (which is available online, so the example must be reproducible):</p>
<p><code><br />
regs &lt;- list(Africa="Africa",Americas="Americas",Asia="Asia")<br />
cols &lt;- c(Africa="red",Americas="green",Asia="blue")<br />
url &lt;- "http://storage.ggki.hu/~nattomi/ryouready/20100303"<br />
x &lt;- lapply(regs, function(x) {read.table(file.path(url,x),header=TRUE)})</code></p>
<p>Before plotting, I determine the range of the plottted values.<br />
<code><br />
data(world.dat) # data used for plotting a world map<br />
zAxs &lt;- unlist(lapply(x,function(x) x$fnERT1))<br />
r &lt;- range(zAxs)<br />
</code></p>
<p>And finally, the interactive plot itself:<br />
<code><br />
playwith({plot3d(world.dat$x,world.dat$y,lowZ,pch=".",<br />
zlim=c(lowZ,upZ),xlab="longitude",</code><br />
<code> ylab="latitude",zlab="F1 (Hz)",<br />
theta=theta,phi=phi,ticktype="detailed")<br />
for (i in regs) {<br />
d &lt;- x[[i]]<br />
points3d(d$Dc,d$Hc,d$fnERT1,col=cols[[i]],pch=".")<br />
}},<br />
parameters=list(<br />
theta=seq(0,360,by=5),<br />
phi=seq(0,90,by=5),<br />
lowZ=seq(r[1],r[2],0.5),<br />
upZ=seq(r[2],r[1],-0.5)))</code></p>
<p>You should see a window popping up with 4 sliders allowing you to set different paramters of the plot, for example vertical and horizontal rotation. You can already see from the example that the syntax of the <em>playwith</em> command is very simple, you specify a set of commands necessary for creating the plot (with possible parameters included such as <em>theta</em> in this example) between curly braces then a list specifying values to be looped through for the parameters. What more could I say? If you are a visual type (or your boss is one) then play with <em>playwith</em>!</p>
<p><strong>Remark 1</strong>: Installing the package <em>R.basic</em> goes in a little bit unusual way, see <a href="http://www.braju.com/R/">http://www.braju.com/R/</a> for details.</p>
<p><strong>Remark 2</strong>: My world map is just a plot of a cloud of points on the plane. It would be nice if the points would be connected accordingly. This can be achieved by using the <em>world()</em> command in the <em>fields</em> package although I wasn&#8217;t able to integrate this into the 3d display. Any suggestions are very welcome. The <em>world.dat</em> dataset has an another drawback: it doesn&#8217;t include <a href="http://www.openstreetmap.org/?lat=40.77&amp;lon=11.01&amp;zoom=7&amp;layers=B000FTF">Corsica and Sardinia</a> so this world map is not of too much use for the locals.</p>
<p style="text-align:center;"><a href="http://ryouready.files.wordpress.com/2010/03/playwith.png"><img class="aligncenter size-full wp-image-546" style="border:0 none;" title="playwith" src="http://ryouready.files.wordpress.com/2010/03/playwith.png?w=500&#038;h=295" alt="" width="500" height="295" /></a></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/ryouready.wordpress.com/528/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/ryouready.wordpress.com/528/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ryouready.wordpress.com&#038;blog=5891102&#038;post=528&#038;subd=ryouready&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://ryouready.wordpress.com/2010/03/23/playing-with-the-playwith-package/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
	
		<media:content url="http://2.gravatar.com/avatar/e3ad8a0573770cdb9606d7550ca730c2?s=96&#38;d=http%3A%2F%2F2.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96" medium="image">
			<media:title type="html">Tamás</media:title>
		</media:content>

		<media:content url="http://ryouready.files.wordpress.com/2010/03/playwith_demo.png?w=300" medium="image">
			<media:title type="html">playwith_demo</media:title>
		</media:content>

		<media:content url="http://ryouready.files.wordpress.com/2010/03/playwith.png" medium="image">
			<media:title type="html">playwith</media:title>
		</media:content>
	</item>
		<item>
		<title>R vs. Matlab &#8211; a small example</title>
		<link>http://ryouready.wordpress.com/2010/02/15/r-vs-matlab/</link>
		<comments>http://ryouready.wordpress.com/2010/02/15/r-vs-matlab/#comments</comments>
		<pubDate>Mon, 15 Feb 2010 19:26:23 +0000</pubDate>
		<dc:creator>nattomi</dc:creator>
				<category><![CDATA[R / R-Code]]></category>
		<category><![CDATA[Matlab]]></category>
		<category><![CDATA[plotrix]]></category>
		<category><![CDATA[R]]></category>

		<guid isPermaLink="false">http://ryouready.wordpress.com/?p=504</guid>
		<description><![CDATA[At the institute I&#8217;m working quite a lot of people prefer using Matlab and only a few of them know about R. Today one of my colleagues &#8212; who is also an eager user of Matlab &#8212; ran into the following problem: He had a vector in hand which consisted of elements. He wanted to [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ryouready.wordpress.com&#038;blog=5891102&#038;post=504&#038;subd=ryouready&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>At the <a href="http://www.ggki.hu/">institute</a> I&#8217;m working quite a lot of people prefer using Matlab and only a few of them know about R. Today one of my colleagues &#8212; who is also an eager user of Matlab &#8212; ran into the following problem:</p>
<ul>
<li>He had a vector <img src='http://s0.wp.com/latex.php?latex=v&amp;bg=ffffff&amp;fg=333333&amp;s=0' alt='v' title='v' class='latex' /> in hand which consisted of <img src='http://s0.wp.com/latex.php?latex=%5Cfrac%7Bn%28n%2B1%29%7D%7B2%7D&amp;bg=ffffff&amp;fg=333333&amp;s=0' alt='&#92;frac{n(n+1)}{2}' title='&#92;frac{n(n+1)}{2}' class='latex' /> elements.</li>
<li>He wanted to reshape this data into an n×n matrix <img src='http://s0.wp.com/latex.php?latex=M&amp;bg=ffffff&amp;fg=333333&amp;s=0' alt='M' title='M' class='latex' />, where the element <img src='http://s0.wp.com/latex.php?latex=M_%7Bij%7D&amp;bg=ffffff&amp;fg=333333&amp;s=0' alt='M_{ij}' title='M_{ij}' class='latex' /> is equal to <img src='http://s0.wp.com/latex.php?latex=v_%7Bk%2Bj%7DI%28j%3C%3Dn-i%2B1%29&amp;bg=ffffff&amp;fg=333333&amp;s=0' alt='v_{k+j}I(j&lt;=n-i+1)' title='v_{k+j}I(j&lt;=n-i+1)' class='latex' /> with <img src='http://s0.wp.com/latex.php?latex=k%3D%5Cfrac%7B%282n-i%2B2%29%28i-1%29%7D%7B2%7D&amp;bg=ffffff&amp;fg=333333&amp;s=0' alt='k=&#92;frac{(2n-i+2)(i-1)}{2}' title='k=&#92;frac{(2n-i+2)(i-1)}{2}' class='latex' /> and <img src='http://s0.wp.com/latex.php?latex=I%28j+%3C%3D+n-i%2B1%29%3D1&amp;bg=ffffff&amp;fg=333333&amp;s=0' alt='I(j &lt;= n-i+1)=1' title='I(j &lt;= n-i+1)=1' class='latex' /> if the condition <img src='http://s0.wp.com/latex.php?latex=j+%3C%3D+n-i%2B1&amp;bg=ffffff&amp;fg=333333&amp;s=0' alt='j &lt;= n-i+1' title='j &lt;= n-i+1' class='latex' /> is satisfied and <img src='http://s0.wp.com/latex.php?latex=0&amp;bg=ffffff&amp;fg=333333&amp;s=0' alt='0' title='0' class='latex' /> otherwise. In other words, the first <img src='http://s0.wp.com/latex.php?latex=%28n-i%2B1%29&amp;bg=ffffff&amp;fg=333333&amp;s=0' alt='(n-i+1)' title='(n-i+1)' class='latex' />th element of the <img src='http://s0.wp.com/latex.php?latex=i&amp;bg=ffffff&amp;fg=333333&amp;s=0' alt='i' title='i' class='latex' />th row of <img src='http://s0.wp.com/latex.php?latex=M&amp;bg=ffffff&amp;fg=333333&amp;s=0' alt='M' title='M' class='latex' /> is equal to the vector <img src='http://s0.wp.com/latex.php?latex=%28v_%7Bk%2B1%7D%2Cv_%7Bk%2B2%7D%2C%5Cldots%2Cv_%7Bk%2Bn-i%2B1%7D%29&amp;bg=ffffff&amp;fg=333333&amp;s=0' alt='(v_{k+1},v_{k+2},&#92;ldots,v_{k+n-i+1})' title='(v_{k+1},v_{k+2},&#92;ldots,v_{k+n-i+1})' class='latex' /> and the remaining elements are zero.</li>
</ul>
<p>He struggled for long minutes of how he should design a loop for doing this task. Of course writing such a loop is not a highly difficult task, but why would we waste our time, if we can get the same result in a single line of R code?</p>
<p><span id="more-504"></span>For the sake of illustration, I&#8217;ve generated an input vector for the case of <img src='http://s0.wp.com/latex.php?latex=n%3D99&amp;bg=ffffff&amp;fg=333333&amp;s=0' alt='n=99' title='n=99' class='latex' /> (the value of <img src='http://s0.wp.com/latex.php?latex=n&amp;bg=ffffff&amp;fg=333333&amp;s=0' alt='n' title='n' class='latex' /> was 99 in my colleague&#8217;s problem as well):</p>
<p><code>v &lt;- rep(99:1,times=99:1)</code></p>
<p>and used the one-liner</p>
<p><code>M &lt;- t(matrix(unlist(tapply(v,rep(1:99,times=99:1),function(x) c(x,rep(0,99-length(x))))),nrow=99))</code></p>
<p>This is the kind of compactness I like pretty much in R. At the end I would like to emphasize that this post is not against Matlab, it just points out how the different logic of the R language can simplify problem solving in many situations. As a bonus let me share the visualization of the resulted matrix using the color2D.matplot function of the <a href="http://cran.r-project.org/web/packages/plotrix/index.html">plotrix</a> package:<br />
<code><br />
library(plotrix)<br />
color2D.matplot(M,c(0,1),c(1,0),c(0,0))</code></p>
<p><a href="http://ryouready.files.wordpress.com/2010/02/matrix.jpg"><img class="alignnone size-medium wp-image-518" title="matrix" src="http://ryouready.files.wordpress.com/2010/02/matrix.jpg?w=300&#038;h=300" alt="" width="300" height="300" /></a></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/ryouready.wordpress.com/504/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/ryouready.wordpress.com/504/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ryouready.wordpress.com&#038;blog=5891102&#038;post=504&#038;subd=ryouready&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://ryouready.wordpress.com/2010/02/15/r-vs-matlab/feed/</wfw:commentRss>
		<slash:comments>12</slash:comments>
	
		<media:content url="http://2.gravatar.com/avatar/e3ad8a0573770cdb9606d7550ca730c2?s=96&#38;d=http%3A%2F%2F2.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96" medium="image">
			<media:title type="html">Tamás</media:title>
		</media:content>

		<media:content url="http://ryouready.files.wordpress.com/2010/02/matrix.jpg?w=300" medium="image">
			<media:title type="html">matrix</media:title>
		</media:content>
	</item>
		<item>
		<title>Progress bars in R (part II) &#8211; a wrapper for apply functions</title>
		<link>http://ryouready.wordpress.com/2010/01/11/progress-bars-in-r-part-ii-a-wrapper-for-apply-functions/</link>
		<comments>http://ryouready.wordpress.com/2010/01/11/progress-bars-in-r-part-ii-a-wrapper-for-apply-functions/#comments</comments>
		<pubDate>Sun, 10 Jan 2010 23:55:47 +0000</pubDate>
		<dc:creator>markheckmann</dc:creator>
				<category><![CDATA[R / R-Code]]></category>
		<category><![CDATA[apply]]></category>
		<category><![CDATA[progress bar]]></category>

		<guid isPermaLink="false">http://ryouready.wordpress.com/?p=457</guid>
		<description><![CDATA[In a previous post I gave some examples of how to make a progress bar in R. In the examples the bars were created within loops. Very often though I have situations where I would like have a progress bar when using apply(). The plyr package provides several apply-like functions also including progress bars, so [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ryouready.wordpress.com&#038;blog=5891102&#038;post=457&#038;subd=ryouready&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p><a href="http://ryouready.files.wordpress.com/2010/01/progress_bar_part2.png"><img class="alignleft size-medium wp-image-478" style="margin:10px;" title="progress_bar_part2" src="http://ryouready.files.wordpress.com/2010/01/progress_bar_part2.png?w=300&#038;h=225" alt="" width="300" height="225" /></a>In a <a href="http://ryouready.wordpress.com/2009/03/16/r-monitor-function-progress-with-a-progress-bar/" target="_blank">previous post</a> I gave some examples of how to make a progress bar in R. In the examples the bars were created within loops. Very often though I have situations where I would like have a progress bar when using <tt>apply()</tt>. The <tt>plyr</tt> package provides several <tt>apply</tt>-like functions also including progress bars, so one could have a look here and use a <tt>plyr</tt> function instead of apply if possible. Anyway, here comes a wrapper for <tt>apply</tt>, <tt>lapply</tt> and <tt>sapply</tt> that has a progressbar. It seems to work although one known issue is the use of vectors (like <tt>c(1,2)</tt>with the <tt>MARGIN</tt> argument in <tt>apply_pb()</tt>. Also you can see in the performance comparison below that the wrapper causes overhead to a considerable extent, which is the main drawback of this approach. <span id="more-457"></span></p>
<pre><span style="color:#008000;">###############################################################

# STATUS: WORKING, but only tested once or twice,
# tested with most ?apply examples
# ISSUES/TODO: MARGIN argument cannot take a
# vector like 1:2 that is more than one numeric</span>

<span style="color:#333399;">apply_pb &lt;- function(X, MARGIN, FUN, ...)
{
  env &lt;- environment()
  pb_Total &lt;- sum(dim(X)[MARGIN])
  counter &lt;- 0
  pb &lt;- txtProgressBar(min = 0, max = pb_Total,
                       style = 3)</span>

  <span style="color:#333399;">wrapper &lt;- function(...)
  {
    curVal &lt;- get("counter", envir = env)
    assign("counter", curVal +1 ,envir= env)
    setTxtProgressBar(get("pb", envir= env),
                           curVal +1)
    FUN(...)
  }
  res &lt;- apply(X, MARGIN, wrapper, ...)
  close(pb)
  res
}</span>

<span style="color:#008000;">## NOT RUN:
# apply_pb(anscombe, 2, sd, na.rm=TRUE)

## large dataset
# df &lt;- data.frame(rnorm(30000), rnorm(30000))
# apply_pb(df, 1, sd)

###############################################################</span>

<span style="color:#333399;">lapply_pb &lt;- function(X, FUN, ...)
{
 env &lt;- environment()
 pb_Total &lt;- length(X)
 counter &lt;- 0
 pb &lt;- txtProgressBar(min = 0, max = pb_Total, style = 3)   

 # wrapper around FUN
 wrapper &lt;- function(...){
   curVal &lt;- get("counter", envir = env)
   assign("counter", curVal +1 ,envir=env)
   setTxtProgressBar(get("pb", envir=env), curVal +1)
   FUN(...)
 }
 res &lt;- lapply(X, wrapper, ...)
 close(pb)
 res
}</span>

<span style="color:#008000;">## NOT RUN:
# l &lt;- sapply(1:20000, function(x) list(rnorm(1000)))
# lapply_pb(l, mean)</span>

<span style="color:#008000;">###############################################################</span>

<span style="color:#333399;">sapply_pb &lt;- function(X, FUN, ...)
{
  env &lt;- environment()
  pb_Total &lt;- length(X)
  counter &lt;- 0
  pb &lt;- txtProgressBar(min = 0, max = pb_Total, style = 3)

  wrapper &lt;- function(...){
    curVal &lt;- get("counter", envir = env)
    assign("counter", curVal +1 ,envir=env)
    setTxtProgressBar(get("pb", envir=env), curVal +1)
    FUN(...)
  }
  res &lt;- sapply(X, wrapper, ...)
  close(pb)
  res
}</span><span style="color:#008000;">

## NOT RUN:</span>
<span style="color:#008000;"># l &lt;- sapply(1:20000, function(x) list(rnorm(1000))
# sapply_pb(l, mean)</span><span style="color:#008000;">

###############################################################</span></pre>
<p>Nice up to now, but now let&#8217;s see what the difference in performance due to the wrapper overhead looks like.</p>
<pre><span style="color:#008000;">###############################################################</span>

&gt; l &lt;- sapply(1:20000, function(x) list(rnorm(1000)))
&gt; system.time(sapply(l, mean))
User      System    verstrichen
0.474       0.003       0.475
&gt; system.time(sapply_pb(l, mean))
|======================================================| 100%
User      System    verstrichen
1.863       0.025       1.885

&gt; df &lt;- data.frame(rnorm(90000), rnorm(90000))
&gt; system.time(apply(df, 1, sd))
User      System verstrichen
7.152       0.062       7.260
&gt; system.time(apply_pb(df, 1, sd))
|======================================================| 100%
User      System     verstrichen
13.112       0.099      13.192

<span style="color:#008000;">###############################################################</span></pre>
<p>So, what we see is that performance radically goes down. This is extremely problematic in our context as one will tend to use progress bars in situations where processing times are already quite long. So if someone has an improvement for that I would be glad to hear about it.</p>
<p>Latest version with more comments on <a href="http://github.com/markheckmann/MHmisc/blob/master/apply_with_progressbar.r" target="_blank">github</a>.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/ryouready.wordpress.com/457/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/ryouready.wordpress.com/457/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ryouready.wordpress.com&#038;blog=5891102&#038;post=457&#038;subd=ryouready&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://ryouready.wordpress.com/2010/01/11/progress-bars-in-r-part-ii-a-wrapper-for-apply-functions/feed/</wfw:commentRss>
		<slash:comments>12</slash:comments>
	
		<media:content url="http://2.gravatar.com/avatar/80731da9aeab670f39dfa6f74a306222?s=96&#38;d=http%3A%2F%2F2.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96" medium="image">
			<media:title type="html">markheckmann</media:title>
		</media:content>

		<media:content url="http://ryouready.files.wordpress.com/2010/01/progress_bar_part2.png?w=300" medium="image">
			<media:title type="html">progress_bar_part2</media:title>
		</media:content>
	</item>
		<item>
		<title>Infomaps using R &#8211; Visualizing German unemployment rates by district on a map</title>
		<link>http://ryouready.wordpress.com/2009/11/16/infomaps-using-r-visualizing-german-unemployment-rates-by-color-on-a-map/</link>
		<comments>http://ryouready.wordpress.com/2009/11/16/infomaps-using-r-visualizing-german-unemployment-rates-by-color-on-a-map/#comments</comments>
		<pubDate>Mon, 16 Nov 2009 12:12:01 +0000</pubDate>
		<dc:creator>markheckmann</dc:creator>
				<category><![CDATA[R / R-Code]]></category>
		<category><![CDATA[maps]]></category>
		<category><![CDATA[R]]></category>
		<category><![CDATA[visualization]]></category>

		<guid isPermaLink="false">http://ryouready.wordpress.com/?p=392</guid>
		<description><![CDATA[Lately, David Smith from REvolution Computing set out to challenge the R community with the reprocuction of a beautiful choropleth map (= multiple regions map/thematic map) on US unemployment rates he had seen on the Flowing Data blog. Here you can find the impressing results. Being a fan of beautiful visualizations I tried to produce [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ryouready.wordpress.com&#038;blog=5891102&#038;post=392&#038;subd=ryouready&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p><a href="http://ryouready.files.wordpress.com/2009/11/germany_by_unemployment_shapefile.png"><img class="alignleft size-medium wp-image-404" title="germany_by_unemployment_shapefile" src="http://ryouready.files.wordpress.com/2009/11/germany_by_unemployment_shapefile.png?w=300&#038;h=300" alt="germany_by_unemployment_shapefile" width="300" height="300" /></a>Lately, David Smith from <a href="http://www.revolution-computing.com/" target="_blank">REvolution Computing</a> set out to <a href="http://blog.revolution-computing.com/2009/11/choropleth-challenge-result.html" target="_blank">challenge the R community</a> with the reprocuction of a beautiful choropleth map (= multiple regions map/thematic map) on US unemployment rates he had seen on the <a href="http://flowingdata.com/2009/11/12/how-to-make-a-us-county-thematic-map-using-free-tools/" target="_blank">Flowing Data blog</a>. <a href="http://blog.revolution-computing.com/2009/11/choropleth-challenge-result.html" target="_self">Here</a> you can find the impressing results. Being a fan of beautiful visualizations I tried to produce a similar map for Germany.</p>
<p><strong>1. </strong><strong>Getting the spatial country data</strong></p>
<p>The first step resulted in getting<strong> </strong>data to draw a map of the German administrative districts. Unfortunately, the maps for Germany do not come along in the <tt>map</tt> package, which would mean I could easily adopt the code results from the challenge. Getting data: The <a href="http://gadm.org/" target="_blank">GADM database of Global Administrative Areas</a> has the aim to provide data of administrative districts for the whole world on different levels (country, state and county level). The data can be downloaded as as a shapefile, an ESRI geodatabase file, a Google Earth .kmz file and very convenient for R users, as an Rdata file.<strong> </strong><strong><br />
</strong></p>
<p><strong>2. </strong><strong>Getting socio-demographic data</strong> (e. g. unemployment rates by administrative district): A lot of data is available online at <a href="http://www.statistikportal.de/" target="_blank">www.statistikportal.de</a>. On this site you find links to several data bases. To get the unemployment stats by county I clicked my way through: <em>Regionaldatenbank Deutschland -&gt; Arbeitsmarkt -&gt; Arbeitsmarktstatistik der Bundesagentur für Arbeit -&gt; Arbeitslose nach ausgewählten Personengruppen sowie Arbeitslosenquoten &#8211; Jahresdurchschnitt &#8211; (ab 2008) regionale Tiefe: Kreise und krfr. Städte -&gt; Werteabruf -&gt; save as CSV format</em>. This table contains all the information I need, although for some reson, for a few districts there is no data listed. I also looked for another source. On <a href="http://ims.destatis.de/indikatoren/" target="_blank">Regionalatlas</a> a nice online visualization tool is offered. In the menu I selected unemployment rate 2008 as indicator. Besides the nice visualization you get, there is a menu button &#8220;tables&#8221; where you can retrieve a html table of the data. I simply copied and pasted it into a .txt file which gives me a tab seperated value format I can read in R. But still: some districts are not listed. <a href="http://ryouready.files.wordpress.com/2009/11/data_germany_unemployment_by_county.pdf" target="_blank">Here</a> is a pdf file containing the data.<span id="more-392"></span></p>
<p><strong>3. </strong><strong>Preparing the data</strong></p>
<p>Now I have two datafiles: One (gadm) containaing the spatial information, the other one (unempl) containing the unemployment rates. It turns out that the same districts are not always named alike. Sometimes the name comes along with a supplement or in other cases the deviations are more severe so that simple parsing will not do it.</p>
<p><strong><a href="http://ryouready.files.wordpress.com/2009/11/unemployment_names_comparison.png"><img class="size-full wp-image-398 alignnone" title="unemployment_names_comparison" src="http://ryouready.files.wordpress.com/2009/11/unemployment_names_comparison.png?w=500&#038;h=231" alt="unemployment_names_comparison" width="500" height="231" /></a></strong></p>
<p>I decided to take the quick-and-dirty route and do a fuzzy matching, which surely is prone to errors, very slow and not at all elegant&#8230; Well, never underestimate the rawness of raw data.</p>
<p><strong>4. Plotting the data</strong></p>
<p>On Claudia Engel&#8217;s <a href="http://www.stanford.edu/~cengel/cgi-bin/anthrospace/download-global-administrative-areas-as-rdata-files" target="_blank">Anthrospace blog</a> I found an R script already perfect to make use of the data provided. The Rdata files turn out to contain <tt>SpatialPolygonsDataFrame</tt> so we can print the data without any further preparation using the <tt>sp</tt> package.</p>
<pre><span style="color:#339966;">###############################################################</span><span style="color:#333399;"><span style="color:#339966;">
</span></span><span style="color:#333399;">library(sp)
library(RColorBrewer)</span>

<span style="color:#333399;"># get spatial data for Germany on county level</span>
con &lt;- url("http://gadm.org/data/rda/DEU_adm3.RData")
print(load(con))
close(con)
<span style="color:#333399;"><span style="color:#339966;"># plot Germany with random colors</span>
col = rainbow(length(levels(gadm$NAME_3)))
spplot(gadm, "NAME_3", col.regions=col, main="German Regions",
       colorkey = FALSE, lwd=.4, col="white")</span>
<span style="color:#339966;">###############################################################</span>
</pre>
<p><a href="http://ryouready.files.wordpress.com/2009/11/germany_random1.png"><img class="alignnone size-full wp-image-402" title="germany_random" src="http://ryouready.files.wordpress.com/2009/11/germany_random1.png?w=500" alt="germany_random"   /></a></p>
<p>This looks nice. To produce a color vector to visualize the unemployment rate the two data sets have to be merged.</p>
<pre><span style="color:#339966;">###############################################################
</span><span style="color:#333399;"><span style="color:#339966;">### DATA PREP ###</span>
<span style="color:#339966;"># loading the unemployment data</span>
unempl &lt;- read.delim2(file="./data/data_germany_unemployment_by_
                     county.txt", header = TRUE, sep = "\t",
                     dec=",", stringsAsFactors=F)</span><span style="color:#339966;">

# due to Mac OS encoding, otherwise not needed</span><span style="color:#333399;">
gadm_names &lt;- iconv(gadm$NAME_3, "ISO_8859-2", "UTF-8")  </span><span style="color:#339966;"> </span>

<pre><span style="color:#333399;"><span style="color:#339966;"># fuzzy matching of data: quick &amp; dirty
</span></span><span style="color:#339966;"># caution: this step takes some time ~ 2 min.</span><span style="color:#333399;">

</span><span style="color:#339966;"># parsing out "Städte"</span><span style="color:#333399;">
gadm_names_n &lt;- gsub("Städte", "", gadm_names)</span><span style="color:#339966;"> </span><span style="color:#333399;">

total &lt;- length(gadm_names)</span><span style="color:#339966;">
# create progress bar</span><span style="color:#333399;">
pb &lt;- txtProgressBar(min = 0, max = total, style = 3) </span>
<span style="color:#333399;">order &lt;- vector()</span><span style="color:#333399;">
for (i in 1:total){</span>  <span style="color:#333399;"><span style="color:#333399;">
   order[i] &lt;- agrep(g</span>adm_names_n[i], unempl$Landkreis, </span><span style="color:#333399;">
                     max.distance = 0.2)[1]</span>
 <span style="color:#333399;">setTxtProgressBar(pb, i)</span>               <span style="color:#339966;"># update progress bar</span><span style="color:#333399;">
}</span>

<pre>
<pre><span style="color:#333399;"><span style="color:#339966;"># choose color by unemployment rate</span></span>
<span style="color:#333399;">col_no &lt;- as.factor(as.numeric(cut(unempl$Wert[order],</span>
<span style="color:#333399;">                    c(0,2.5,5,7.5,10,15,100))))
levels(col_no) &lt;- c("&gt;2,5%", "2,5-5%", "5-7,5%",
                    "7,5-10%", "10-15%", "&gt;15%")
gadm$col_no &lt;- col_no
myPalette&lt;-brewer.pal(6,"Purples")</span>

<span style="color:#339966;"># plotting</span>
<span style="color:#333399;">spplot(gadm, "col_no", col=grey(.9), col.regions=myPalette,
main="Unemployment in Germany by district")</span><span style="color:#339966;">

###############################################################</span></pre>
<p><a href="http://ryouready.files.wordpress.com/2009/11/germany_by_unemployment.png"><img class="alignnone size-full wp-image-403" title="germany_by_unemployment" src="http://ryouready.files.wordpress.com/2009/11/germany_by_unemployment.png?w=500" alt="germany_by_unemployment"   /></a></p>
<p><span style="color:#000000;">It seems that the districts for which no data was available mainly belong to the states Sachsen-Anhalt and Sachsen. Also you can see that east of Germany has got a much higher unemplyoment rate than the west. The same holds true for a north-south comparison.</span></p>
<p><span style="color:#000000;">Besides ths <tt>sp</tt> package there are many other ways to produce such a graphic. I will now take another approch using shapefile data which also is available on GDAM. The data is availabe as a .zip file which includes several dBase files for all levels (3=district, 1=state etc.).</span></p>
<pre>
<pre><span style="color:#339966;">###############################################################</span>

<pre><span style="color:#333399;">library(sp)
library(maptools)</span>

<span style="color:#333399;">nc1 &lt;- readShapePoly("./data/DEU_adm/DEU_adm1.dbf",</span>
<span style="color:#333399;">                    proj4string=CRS("+proj=longlat +datum=NAD27"))</span><span style="color:#333399;">
nc3 &lt;- readShapePoly("./data/DEU_adm/DEU_adm3.dbf",
                    proj4string=CRS("+proj=longlat +datum=NAD27"))</span>

<span style="color:#339966;"># col_no comes from the calculations above</span><span style="color:#333399;">
par(mar=c(0,0,0,0))</span>
<span style="color:#333399;">plot(nc3, col=myPalette[col_no], border=grey(.9), lwd=.5)
plot(nc1, col=NA, border=grey(.5), lwd=1, add=TRUE)</span>

<span style="color:#339966;">###############################################################</span></pre>
<p><a href="http://ryouready.files.wordpress.com/2009/11/germany_by_unemployment_shapefile.png"><img title="germany_by_unemployment_shapefile" src="http://ryouready.files.wordpress.com/2009/11/germany_by_unemployment_shapefile.png?w=480&#038;h=480" alt="germany_by_unemployment_shapefile" width="480" height="480" /></a></p>
<p><span style="color:#000000;">What I like about all this, it that it is pretty simple to draw almost any country you like. Besides the very messy part of data preparation it is only a few lines of code and the results are nice.</span></p>
<pre>
<pre> 
</pre>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/ryouready.wordpress.com/392/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/ryouready.wordpress.com/392/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ryouready.wordpress.com&#038;blog=5891102&#038;post=392&#038;subd=ryouready&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://ryouready.wordpress.com/2009/11/16/infomaps-using-r-visualizing-german-unemployment-rates-by-color-on-a-map/feed/</wfw:commentRss>
		<slash:comments>25</slash:comments>
	
		<media:content url="http://2.gravatar.com/avatar/80731da9aeab670f39dfa6f74a306222?s=96&#38;d=http%3A%2F%2F2.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96" medium="image">
			<media:title type="html">markheckmann</media:title>
		</media:content>

		<media:content url="http://ryouready.files.wordpress.com/2009/11/germany_by_unemployment_shapefile.png?w=300" medium="image">
			<media:title type="html">germany_by_unemployment_shapefile</media:title>
		</media:content>

		<media:content url="http://ryouready.files.wordpress.com/2009/11/unemployment_names_comparison.png" medium="image">
			<media:title type="html">unemployment_names_comparison</media:title>
		</media:content>

		<media:content url="http://ryouready.files.wordpress.com/2009/11/germany_random1.png" medium="image">
			<media:title type="html">germany_random</media:title>
		</media:content>

		<media:content url="http://ryouready.files.wordpress.com/2009/11/germany_by_unemployment.png" medium="image">
			<media:title type="html">germany_by_unemployment</media:title>
		</media:content>

		<media:content url="http://ryouready.files.wordpress.com/2009/11/germany_by_unemployment_shapefile.png" medium="image">
			<media:title type="html">germany_by_unemployment_shapefile</media:title>
		</media:content>
	</item>
		<item>
		<title>R: Function to create tables in LaTex or Lyx to display regression model results</title>
		<link>http://ryouready.wordpress.com/2009/06/19/r-function-to-create-tables-in-latex-or-lyx-to-display-regression-models-results/</link>
		<comments>http://ryouready.wordpress.com/2009/06/19/r-function-to-create-tables-in-latex-or-lyx-to-display-regression-models-results/#comments</comments>
		<pubDate>Fri, 19 Jun 2009 16:41:38 +0000</pubDate>
		<dc:creator>markheckmann</dc:creator>
				<category><![CDATA[R / R-Code]]></category>
		<category><![CDATA[LaTex]]></category>
		<category><![CDATA[Lyx]]></category>
		<category><![CDATA[regression]]></category>
		<category><![CDATA[sweave]]></category>
		<category><![CDATA[tables]]></category>

		<guid isPermaLink="false">http://ryouready.wordpress.com/?p=356</guid>
		<description><![CDATA[Most people using LaTex feel that creating tables is no fun. Some days ago I stumbled across a neat function written by Paul Johnson that produces LaTex code as well as LaTex code that can be used within Lyx. The output can be used for regression models and looks like output from the Stata outreg [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ryouready.wordpress.com&#038;blog=5891102&#038;post=356&#038;subd=ryouready&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p><img class="alignleft size-medium wp-image-358" style="margin:6px;" title="regression_models_in_latex" src="http://ryouready.files.wordpress.com/2009/06/regression_models_in_latex.png?w=240&#038;h=199" alt="regression_models_in_latex" width="240" height="199" />Most people using LaTex feel that creating tables is no fun. Some days ago I stumbled across a neat function written by <a href="http://pj.freefaculty.org/" target="_blank">Paul Johnson</a> that produces LaTex code as well as LaTex code that can be used within <a href="www.lyx.org" target="_blank">Lyx</a>. The output can be used for regression models and looks like output from the Stata <tt>outreg</tt> command. His R function that produces the LaTex code has the same name:  <tt>outreg()</tt>. The <tt>outreg </tt>code can be found on his <a href="http://pj.freefaculty.org/R/outreg-worked.R" target="_blank">website</a> or in the <a href="http://ryouready.files.wordpress.com/2009/06/outreg_code_by_paul_johnson.pdf" target="_blank">PDF copy</a> of the code from his website.</p>
<p>I took the code, put it into a <tt>.rnw</tt> file and sweaved it. It worked like a charm and produced beautiful results (see the picture on the left and the <a href="http://ryouready.files.wordpress.com/2009/06/regression_for_latex_and_sweave.pdf" target="_blank">PDF</a>). Below you can find the code for the noweb file (.rnw). Latex code is colored grey, R-code is colored blue. Just have a look at all the results as a <a href="http://ryouready.files.wordpress.com/2009/06/regression_for_latex_and_sweave.pdf">PDF</a> file. Besides, Paul Johnson has also created a nice <a href="http://pj.freefaculty.org/R/Rtips.html" target="_blank">list of R-Tips</a> that can be found on his website as well.</p>
<p><span id="more-356"></span></p>
<p><span style="color:#000080;"><span style="color:#008000;"> </span></span></p>
<pre><span style="color:#000080;"><span style="color:#008000;">###############################################################</span>

</span><span style="color:#808080;">\documentclass[a4paper,10pt]{article}

\title{Regression Tables for LaTex}
\auth<span style="color:#888888;">or{</span></span><span style="color:#888888;">Mark Heckmann. Code by Paul Johnson</span><span style="color:#808080;"><span style="color:#888888;">}
\date{\today}</span>

\begin{document}
\maketitle

&lt;&lt;echo=FALSE&gt;&gt;=
<span style="color:#333399;">x1 &lt;- rnorm(100)
x2 &lt;- rnorm(100)
y1 &lt;- 5*rnorm(100)+3*x1 + 4*x2
y2 &lt;- rnorm(100)+5*x2
m1 &lt;- lm (y1~x1)
m2 &lt;- lm (y1~x2)
m3 &lt;- lm (y1 ~ x1 + x2)
gm1 &lt;- glm(y1~x1)</span>
@

&lt;&lt;echo=FALSE, results=tex&gt;&gt;=
<span style="color:#333399;"> outreg(m1,title="My One Tightly Printed Regression", lyx=F )
 outreg(m1,tight=F,modelLabels=c("Fingers"),
        title="My Only Spread Out Regressions" ,lyx=F)
 outreg(list(m1,m2),modelLabels=c("Mine","Yours"),
        varLabels=list(x1="Billie"),
        title="My Two Linear Regressions Tightly Printed" ,lyx=F)
 outreg(list(m1,m2),modelLabels=c("Whatever","Whichever"),
        title="My Two Linear Regressions Not Tightly  Printed",
        showAIC=F, lyx=F)
 outreg(list(m1,m2,m3),title="My Three Linear Regressions", lyx=F)
 outreg(list(m1,m2,m3),tight=F,
        modelLabels=c("I Love love love really long titles",
        "Hate Long","Medium"), lyx=F)
 outreg(list(gm1),modelLabels=c("GLM"), lyx=F)
 outreg(list(m1,gm1),modelLabels=c("OLS","GLM"), lyx=F)</span>
@

\end{document}</span><span style="color:#000080;">
<span style="color:#008000;">
###############################################################
</span></span></pre>
<p><span style="color:#000080;"><span style="color:#008000;"> </span></span></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/ryouready.wordpress.com/356/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/ryouready.wordpress.com/356/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ryouready.wordpress.com&#038;blog=5891102&#038;post=356&#038;subd=ryouready&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://ryouready.wordpress.com/2009/06/19/r-function-to-create-tables-in-latex-or-lyx-to-display-regression-models-results/feed/</wfw:commentRss>
		<slash:comments>15</slash:comments>
	
		<media:content url="http://2.gravatar.com/avatar/80731da9aeab670f39dfa6f74a306222?s=96&#38;d=http%3A%2F%2F2.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96" medium="image">
			<media:title type="html">markheckmann</media:title>
		</media:content>

		<media:content url="http://ryouready.files.wordpress.com/2009/06/regression_models_in_latex.png?w=300" medium="image">
			<media:title type="html">regression_models_in_latex</media:title>
		</media:content>
	</item>
	</channel>
</rss>
