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

<channel>
	<title>Keep on Fighting!</title>
	<atom:link href="http://yihui.name/en/feed/" rel="self" type="application/rss+xml" />
	<link>http://yihui.name/en</link>
	<description>Yihui Xie</description>
	<lastBuildDate>Thu, 18 Feb 2010 19:18:56 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
		
<!-- Start Of Script Generated By WP-PostViews Plus -->
<script type='text/javascript' src='http://yihui.name/en/wp-includes/js/jquery/jquery.js?ver=1.3.2'></script>
<script type="text/javascript">
/* <![CDATA[ */
/* ]]> */
</script>
<!-- End Of Script Generated By WP-PostViews Plus -->
	<item>
		<title>Press Enter in LyX Sweave as You Wish</title>
		<link>http://yihui.name/en/2010/02/press-enter-in-lyx-sweave-as-you-wish/</link>
		<comments>http://yihui.name/en/2010/02/press-enter-in-lyx-sweave-as-you-wish/#comments</comments>
		<pubDate>Thu, 18 Feb 2010 19:15:55 +0000</pubDate>
		<dc:creator>Yihui Xie</dc:creator>
				<category><![CDATA[Computer Science]]></category>
		<category><![CDATA[R Programming]]></category>
		<category><![CDATA[LaTeX]]></category>
		<category><![CDATA[LyX]]></category>
		<category><![CDATA[pgfSweave]]></category>
		<category><![CDATA[R Language]]></category>
		<category><![CDATA[Scrap]]></category>
		<category><![CDATA[Sweave]]></category>

		<guid isPermaLink="false">http://yihui.name/en/?p=443</guid>
		<description><![CDATA[or a long time I&#8217;ve been wondering why we are not able to use Enter in the LyX Scrap environment which was set up by Gregor Gorjanc for Sweave. Two weeks ago, I (finally!) could not help asking Gregor about this issue, as I&#8217;m using &#8220;LyX + Sweave&#8221; more and more in my daily work. [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://yihui.name/en/2010/02/press-enter-in-lyx-sweave-as-you-wish/"><span class="dropcap-green">F</span></a>or a long time I&#8217;ve been wondering why we are not able to use Enter in the LyX Scrap environment which was set up by Gregor Gorjanc for Sweave. Two weeks ago, I (finally!) could not help asking Gregor about this issue, as I&#8217;m using &#8220;LyX + Sweave&#8221; more and more in my daily work. He explained it here: <a href="http://ggorjan.blogspot.com/2009/07/lyx-sweave-mandatory-use-of.html">LyX-Sweave: mandatory use of control+enter in code chunks</a></p>
<p>After digging into the LyX customization manual for a while, I found a solution which allows us to press the Enter key just as we normally do when typing in a LyX document. The key is to use <code>Environment</code> instead of <code>paragraph</code> as <code>LatexType</code> for the style definition of <code>Scrap</code>. Besides, I used the <code>LatexName</code> as <code>wrapsweave</code>, as a <code>LatexName</code> is required by LyX. The definition for <code>wrapsweave</code> is simple: just two empty lines by <code>\par</code>. (If you define it as <code>\newenvironment{wrapsweave}{}{}</code>, you will run into troubles sometimes; especially when you use indent for paragraphs.)</p>
<p>As we know, LaTeX environment cannot be centered in LyX (only paragraphs can), so I defined a special environment <code>ScrapCenter</code> when I want to insert graphics via Sweave and make them center-aligned.<span id="more-443"></span></p>
<p>To put all efforts together, this is the new <code>literate-scrap.inc</code> (compare it with <a href="http://cran.r-project.org/contrib/extra/lyx/literate-scrap.inc">http://cran.r-project.org/contrib/extra/lyx/literate-scrap.inc</a>):</p>
<pre>Format 2

Preamble
\usepackage{Sweave}
\newenvironment{wrapsweave}{\par}{\par}
EndPreamble

OutputType              literate

Style Scrap
  LatexType             Environment
  LatexName             wrapsweave
  Margin                static
  TopSep                0.4
  BottomSep             0.4
  ParSep                0.0
  LabelType             static
  Align                 left
  AlignPossible         block, left, right, center
  NewLine               0
  PassThru              1
  FreeSpacing           1
  TextFont
    Color               latex
    Family              typewriter
  EndFont
End

Style ScrapCenter
  LatexType             Environment
  LatexName             center
  Margin                static
  TopSep                0.4
  BottomSep             0.4
  ParSep                0.0
  LabelType             static
  Align                 center
  NewLine               0
  PassThru              1
  FreeSpacing           1
  TextFont
    Color               latex
    Family              typewriter
  EndFont
End
</pre>
<p>Enjoy pressing a single Enter key in LyX now! <img src='http://yihui.name/en/wp-content/plugins/tango-smilies/tango/face-smile.png' alt=':)' class='wp-smiley' /> </p>
<p>P.S. the side effect of this modification is, your R code will be separated by empty lines. But Sweave will remove blank lines by default, so that is not really a big trouble.</p>
<p>P.P.S. Next time I will write my solution of using <code>pgfSweave</code> in LyX &#8212; if you have never tried the <code>pgfSweave</code> package in R, I&#8217;d strongly recommend you do it right now!! My comment on this package is: amazingly beautiful! See a preview <a href="http://yihui.name/en/wp-content/uploads/2010/02/lyx-pgfsweave-demo.pdf">lyx-pgfsweave-demo</a>.</p>
<h2  class="related_post_title">Related Posts</h2><ul class="related_post"><li><a href="http://yihui.name/en/2009/11/create-animations-in-pdf-documents-using-r/" title="Create Animations in PDF Documents Using R">Create Animations in PDF Documents Using R</a></li><li><a href="http://yihui.name/en/2009/12/happy-new-year-with-r/" title="Happy New Year with R">Happy New Year with R</a></li><li><a href="http://yihui.name/en/2009/12/merry-christmas-using-r/" title="Merry Christmas Using R">Merry Christmas Using R</a></li><li><a href="http://yihui.name/en/2009/10/50000-revisions-committed-to-r/" title="50000 Revisions Committed to R">50000 Revisions Committed to R</a></li><li><a href="http://yihui.name/en/2009/09/how-to-import-ms-excel-data-into-r/" title="How to Import MS Excel Data into R">How to Import MS Excel Data into R</a></li></ul>]]></content:encoded>
			<wfw:commentRss>http://yihui.name/en/2010/02/press-enter-in-lyx-sweave-as-you-wish/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Happy New Year with R</title>
		<link>http://yihui.name/en/2009/12/happy-new-year-with-r/</link>
		<comments>http://yihui.name/en/2009/12/happy-new-year-with-r/#comments</comments>
		<pubDate>Thu, 31 Dec 2009 20:57:47 +0000</pubDate>
		<dc:creator>Yihui Xie</dc:creator>
				<category><![CDATA[R Graphics]]></category>
		<category><![CDATA[Animation]]></category>
		<category><![CDATA[Flash]]></category>
		<category><![CDATA[fun]]></category>
		<category><![CDATA[New Year]]></category>
		<category><![CDATA[polygon()]]></category>
		<category><![CDATA[R Language]]></category>
		<category><![CDATA[saveSWF()]]></category>

		<guid isPermaLink="false">http://yihui.name/en/?p=427</guid>
		<description><![CDATA[I have to admit that the previous post on Christmas is actually not much fun. Today I received another pResent from Yixuan which is more interesting:

Basically the code deals with letter polygons (i.e. glyphs) and plot them with proper projections from 3D to 2D space:
## original code by Yixuan &#60;yixuan.qiu@cos.name&#62;, with my slight modification
h.x = [...]]]></description>
			<content:encoded><![CDATA[<p>I have to admit that the previous post on Christmas is actually not much fun. Today I received another pResent from Yixuan which is more interesting:</p>
<p style="text-align: center;"><object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" width="490" height="280" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0"><param name="src" value="http://yihui.name/en/wp-content/uploads/2009/12/new-year-animation-in-R.swf" /><embed type="application/x-shockwave-flash" width="490" height="280" src="http://yihui.name/en/wp-content/uploads/2009/12/new-year-animation-in-R.swf"></embed></object></p>
<p><span id="more-427"></span>Basically the code deals with letter polygons (i.e. glyphs) and plot them with proper projections from 3D to 2D space:</p>
<pre>## original code by Yixuan &lt;yixuan.qiu@cos.name&gt;, with my slight modification
h.x = c(0.193, 0.295, 0.295, 0.703, 0.703, 0.804, 0.804, 0.703, 0.703,
    0.295, 0.295, 0.193, 0.193)
h.y = c(0.935, 0.935, 0.575, 0.575, 0.935, 0.935, 0.063, 0.063, 0.475,
    0.475, 0.063, 0.063, 0.935)
a1.x = c(0.433, 0.546, 0.865, 0.746, 0.656, 0.328, 0.242, 0.136)
a1.y = c(0.935, 0.935, 0.063, 0.063, 0.326, 0.326, 0.063, 0.063)
a2.x = c(0.488, 0.629, 0.355)
a2.y = c(0.841, 0.418, 0.418)
y.x = c(0.136, 0.259, 0.496, 0.734, 0.853, 0.543, 0.543, 0.441, 0.441)
y.y = c(0.935, 0.935, 0.523, 0.935, 0.935, 0.431, 0.063, 0.063, 0.427)
n.x = c(0.189, 0.295, 0.707, 0.707, 0.804, 0.804, 0.701, 0.287, 0.287, 0.189)
n.y = c(0.935, 0.935, 0.248, 0.935, 0.935, 0.063, 0.063, 0.747, 0.063, 0.063)
e.x = c(0.222, 0.787, 0.787, 0.324, 0.324, 0.757, 0.757, 0.324, 0.324,
    0.804, 0.804, 0.222)
e.y = c(0.935, 0.935, 0.834, 0.834, 0.564, 0.564, 0.464, 0.464, 0.163,
    0.163, 0.063, 0.063)
w.x = c(0, 0.099, 0.254, 0.439, 0.564, 0.738, 0.902, 1, 0.789, 0.687,
    0.5, 0.31, 0.205)
w.y = c(0.935, 0.935, 0.187, 0.935, 0.935, 0.189, 0.935, 0.935, 0.063,
    0.063, 0.826, 0.063, 0.063)
p.x = c(0.218, 0.56, 0.56, 0.56, 0.56, 0.32, 0.32, 0.218, 0.32, 0.32)
p.y = c(0.935, 0.933, 0.832, 0.518, 0.418, 0.418, 0.063, 0.063, 0.518, 0.834)
p.cir.th = seq(pi/2, -pi/2, length.out = 50)
p1.cir.x = 0.56 + 0.2575 * cos(p.cir.th)
p1.cir.y = 0.6755 + 0.2575 * sin(p.cir.th)
p2.cir.x = 0.56 + 0.157 * cos(p.cir.th)
p2.cir.y = 0.6755 + 0.157 * sin(p.cir.th)
p1.x = c(0.218, p1.cir.x, 0.32, 0.32, 0.218)
p1.y = c(0.935, p1.cir.y, 0.418, 0.063, 0.063)
p2.x = c(0.32, p2.cir.x, 0.32)
p2.y = c(0.832, p2.cir.y, 0.518)
r1.cir.th = seq(pi/2, -7/18 * pi, length.out = 50)
r2.cir.th = seq(pi/2, -pi/2, length.out = 50)
r1.cir.x = 0.578 + 0.243 * cos(r1.cir.th)
r1.cir.y = 0.6955 + 0.243 * sin(r1.cir.th)
r2.cir.x = 0.578 + 0.145 * cos(r2.cir.th)
r2.cir.y = 0.6955 + 0.145 * sin(r2.cir.th)
r1.x = c(0.191, r1.cir.x, 0.877, 0.75, 0.54, 0.297, 0.297, 0.191)
r1.y = c(0.937, r1.cir.y, 0.059, 0.059, 0.448, 0.448, 0.059, 0.059)
r2.x = c(0.297, r2.cir.x, 0.297)
r2.y = c(0.841, r2.cir.y, 0.55)
draw.ch = function(x1, y1, x2 = NULL, y2 = NULL, center.x,
    color, alpha, xscale) {
    rgb.col = col2rgb(color)/255
    x1 = x1 * xscale + center.x - 0.5 * xscale
    x2 = x2 * xscale + center.x - 0.5 * xscale
    polygon(x1, y1, col = rgb(rgb.col[1], rgb.col[2], rgb.col[3],
        alpha = alpha), border = NA)
    polygon(x2, y2, col = "black", border = NA)
}
x1 = list(h.x, a1.x, p1.x, p1.x, y.x, n.x, e.x, w.x,
    y.x, e.x, a1.x, r1.x)
y1 = list(h.y, a1.y, p1.y, p1.y, y.y, n.y, e.y, w.y,
    y.y, e.y, a1.y, r1.y)
x2 = list(NULL, a2.x, p2.x, p2.x, NULL, NULL, NULL,
    NULL, NULL, NULL, a2.x, r2.x)
y2 = list(NULL, a2.y, p2.y, p2.y, NULL, NULL, NULL,
    NULL, NULL, NULL, a2.y, r2.y)
th = seq(pi/6, 2 * pi, length.out = 12)
cols = rainbow(200)
## if you don't want to save the animation into SWF,
## just comment the function saveSWF()
saveSWF({
    for (j in 1:238) {
        th = th - pi/120
        center.x = 3 + 5 * cos(th)
        cols = c(cols[-1], cols[1])
        alpha = 0.1 + (50 * (1 - sin(th)))/100
        alpha = ifelse(alpha &gt; 1, 1, alpha)
        xscale = -sin(th) * 1.2
        plot(1, xlim = c(-2, 8), ylim = c(-2.5, 3.5), type = "n")
        plot.order = (1:12)[order(xscale &gt; 0)]
        for (k in 1:12) {
            i = plot.order[k]
            draw.ch(x1[[i]], y1[[i]], x2[[i]], y2[[i]], center.x[i],
                color = cols[k + 60 * ( i &gt;= 6 &amp; i &lt;= 8 ) + 120 *
                    (i &gt; 8)], alpha[i], xscale[i])
        }
        text(8, -2.5, "Yixuan @ 2009-12-31 (http://yixuan.cos.name)",
            adj = c(1, 0), col = "white", cex = 0.8)

    }
}, interval = 0.05, dev = "pdf", para = list(bg = "black", mar = rep(0,
    4)), width = 7, height = 4)
## in the 'fun' package (currently on R-Forge),
## see demo('HappyNewYear2010Yixuan')</pre>
<p>Thanks, Yixuan!</p>
<p>By the way, there are even more interesting demos in the <code>fun</code> package, just install the package by <code>install.packages('fun', repos = 'http://r-forge.r-project.org')</code> to see <code>demo(package = 'fun')$results[, 'Item']</code>.</p>
<h2  class="related_post_title">Related Posts</h2><ul class="related_post"><li><a href="http://yihui.name/en/2009/12/merry-christmas-using-r/" title="Merry Christmas Using R">Merry Christmas Using R</a></li><li><a href="http://yihui.name/en/2009/06/simulation-of-burning-fire-in-r/" title="Simulation of Burning Fire in R">Simulation of Burning Fire in R</a></li><li><a href="http://yihui.name/en/2009/11/create-animations-in-pdf-documents-using-r/" title="Create Animations in PDF Documents Using R">Create Animations in PDF Documents Using R</a></li><li><a href="http://yihui.name/en/2009/10/50000-revisions-committed-to-r/" title="50000 Revisions Committed to R">50000 Revisions Committed to R</a></li><li><a href="http://yihui.name/en/2009/06/creating-tag-cloud-using-r-and-flash-javascript-swfobject/" title="Creating Tag Cloud Using R and Flash / JavaScript (SWFObject)">Creating Tag Cloud Using R and Flash / JavaScript (SWFObject)</a></li></ul>]]></content:encoded>
			<wfw:commentRss>http://yihui.name/en/2009/12/happy-new-year-with-r/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Merry Christmas Using R</title>
		<link>http://yihui.name/en/2009/12/merry-christmas-using-r/</link>
		<comments>http://yihui.name/en/2009/12/merry-christmas-using-r/#comments</comments>
		<pubDate>Thu, 24 Dec 2009 22:50:33 +0000</pubDate>
		<dc:creator>Yihui Xie</dc:creator>
				<category><![CDATA[R Graphics]]></category>
		<category><![CDATA[ani.start()]]></category>
		<category><![CDATA[ani.stop()]]></category>
		<category><![CDATA[Animation]]></category>
		<category><![CDATA[Christmas]]></category>
		<category><![CDATA[Flash]]></category>
		<category><![CDATA[R Language]]></category>
		<category><![CDATA[saveLatex()]]></category>
		<category><![CDATA[saveSWF()]]></category>

		<guid isPermaLink="false">http://yihui.name/en/?p=415</guid>
		<description><![CDATA[Life should be fun. I saw a post in R-help list saying Merry Christmas to other useRs, and I followed up by some R code which can produce a naive animation like this:

Here is the code to generate the above Flash animation with shining Christmas:
library(animation)
saveSWF({
    n = length(speed &#60;- runif(angle &#60;- runif(x [...]]]></description>
			<content:encoded><![CDATA[<p>Life should be fun. I saw a post in R-help list saying Merry Christmas to other useRs, and I followed up by some R code which can produce a naive animation like this:</p>
<div style="text-align: center;"><object style="width: 600px; height: 75px;" classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" width="600" height="75" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0"><param name="src" value="http://yihui.name/en/wp-content/uploads/2009/12/xmas-2009-animation.swf" /><embed style="width: 600px; height: 75px;" type="application/x-shockwave-flash" width="600" height="75" src="http://yihui.name/en/wp-content/uploads/2009/12/xmas-2009-animation.swf"></embed></object></div>
<p>Here is the code to generate the above Flash animation with shining Christmas:</p>
<pre>library(animation)
saveSWF({
    n = length(speed &lt;- runif(angle &lt;- runif(x &lt;- strsplit("MERRY CHRISTMAS",
        "")[[1]], 0, 360), 0, 15))
    for (j in 1:300) {
        angle = angle + speed
        plot.new()
        plot.window(c(1, n), c(0, 1))
        for (i in 1:n) text(i, 0.5, x[i], srt = angle[i], cex = runif(1,
            1, 4), col = sample(colors(), 1))
        text(n, 0, "Yihui @ 2009-12-24 (http://yihui.name)",
            adj = c(1, 0), col = "white", cex = 0.8)
    }
}, interval = 0.04, dev = "pdf", outdir = getwd(), para = list(mar = rep(0,
    4), bg = "black"), width = 8, height = 1)
## in animation package (&gt;=1.1-0), see demo('Xmas')</pre>
<p>There are other animation formats in the R package <code>animation</code>:</p>
<ol>
<li>use <code>saveMovie()</code> to get a GIF animation (need ImageMagick)</li>
<li><code>ani.start()</code> and <code>ani.stop()</code> can produce an HTML page with the animation in it</li>
<li><code>saveLatex()</code> can embed an animation into a PDF document</li>
</ol>
<h2  class="related_post_title">Related Posts</h2><ul class="related_post"><li><a href="http://yihui.name/en/2009/12/happy-new-year-with-r/" title="Happy New Year with R">Happy New Year with R</a></li><li><a href="http://yihui.name/en/2009/06/simulation-of-burning-fire-in-r/" title="Simulation of Burning Fire in R">Simulation of Burning Fire in R</a></li><li><a href="http://yihui.name/en/2009/11/create-animations-in-pdf-documents-using-r/" title="Create Animations in PDF Documents Using R">Create Animations in PDF Documents Using R</a></li><li><a href="http://yihui.name/en/2009/10/50000-revisions-committed-to-r/" title="50000 Revisions Committed to R">50000 Revisions Committed to R</a></li><li><a href="http://yihui.name/en/2009/06/creating-tag-cloud-using-r-and-flash-javascript-swfobject/" title="Creating Tag Cloud Using R and Flash / JavaScript (SWFObject)">Creating Tag Cloud Using R and Flash / JavaScript (SWFObject)</a></li></ul>]]></content:encoded>
			<wfw:commentRss>http://yihui.name/en/2009/12/merry-christmas-using-r/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>Create Animations in PDF Documents Using R</title>
		<link>http://yihui.name/en/2009/11/create-animations-in-pdf-documents-using-r/</link>
		<comments>http://yihui.name/en/2009/11/create-animations-in-pdf-documents-using-r/#comments</comments>
		<pubDate>Thu, 12 Nov 2009 03:37:21 +0000</pubDate>
		<dc:creator>Yihui Xie</dc:creator>
				<category><![CDATA[R Graphics]]></category>
		<category><![CDATA[R Programming]]></category>
		<category><![CDATA[animate]]></category>
		<category><![CDATA[Animation]]></category>
		<category><![CDATA[LaTeX]]></category>
		<category><![CDATA[pdf()]]></category>
		<category><![CDATA[pdflatex]]></category>
		<category><![CDATA[R Language]]></category>

		<guid isPermaLink="false">http://yihui.name/en/?p=335</guid>
		<description><![CDATA[ince animation 1.0-9, we will be able to create a PDF document with an animation embedded in it; the function is saveLatex(), and its usage is similar to saveMovie() and saveSWF(): you pass an R expression for creating animations to this function, and this expression will be evaluated in the function; the image frames get [...]]]></description>
			<content:encoded><![CDATA[<a href="http://yihui.name/en/2009/11/create-animations-in-pdf-documents-using-r/"><span class="dropcap-green">S</span></a>ince <code>animation</code> 1.0-9, we will be able to create a PDF document with an animation embedded in it; the function is <code>saveLatex()</code>, and its usage is similar to <code>saveMovie()</code> and <code>saveSWF()</code>: you pass an R expression for creating animations to this function, and this expression will be evaluated in the function; the image frames get recorded by a graphics device. In the end, a LaTeX document is written in a directory, and we can get a PDF document by running <code>pdflatex</code> on the document.</p>
<p>In fact, the key point is the LaTeX package named <code>animate</code>, which can be used to insert image frames into a PDF document to generate an animation. The interface of animations created by this package is quite similar to the HTML animation page by the R package <code>animation</code>, moreover, it also uses JavaScript (in PDF) to animate the image frames.<span id="more-335"></span></p>
<p>Here is an example:</p>
<pre>library(animation)
oopt = ani.options(interval = 0.1, nmax = 100)
## brownian motion: note the 'loop' option and how to set graphics
#    parameters with 'ani.first'
saveLatex({
    brownian.motion(pch = 21, cex = 5, col = "red", bg = "yellow",
        main = "Demonstration of Brownian Motion")
}, ani.basename = "BM", ani.opts = "controls,loop,width=0.8\\textwidth",
    ani.first = par(mar = c(3, 3, 1, 0.5), mgp = c(2, 0.5, 0),
        tcl = -0.3, cex.axis = 0.8, cex.lab = 0.8, cex.main = 1),
    latex.filename = "brownian.motion.tex")
ani.options(oopt)</pre>
<p><span class="download">Download the demo: <a href="http://yihui.name/en/wp-content/uploads/2009/11/brownian.motion.pdf">Brownian Motion in PDF</a> (205K)</span>
<p>The PDF document will be automatically opened if there is nothing wrong with <code>LaTeX</code> and your PDF viewer; if nothing happened, you can find the PDF document <code>brownian.motion.pdf</code> in the directory <code>ani.options("outdir")</code>.</p>
<p>The animation will work in Acrobat Reader 9.0, and I do not know if other PDF viewers can deal with JavaScript correctly (AFAIK, the default PDF viewer in Mac OS will not).</p>
<h2  class="related_post_title">Related Posts</h2><ul class="related_post"><li><a href="http://yihui.name/en/2010/02/press-enter-in-lyx-sweave-as-you-wish/" title="Press Enter in LyX Sweave as You Wish">Press Enter in LyX Sweave as You Wish</a></li><li><a href="http://yihui.name/en/2009/12/happy-new-year-with-r/" title="Happy New Year with R">Happy New Year with R</a></li><li><a href="http://yihui.name/en/2009/12/merry-christmas-using-r/" title="Merry Christmas Using R">Merry Christmas Using R</a></li><li><a href="http://yihui.name/en/2009/10/50000-revisions-committed-to-r/" title="50000 Revisions Committed to R">50000 Revisions Committed to R</a></li><li><a href="http://yihui.name/en/2009/06/simulation-of-burning-fire-in-r/" title="Simulation of Burning Fire in R">Simulation of Burning Fire in R</a></li></ul>]]></content:encoded>
			<wfw:commentRss>http://yihui.name/en/2009/11/create-animations-in-pdf-documents-using-r/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Some Interesting Packages in R: swfDevice, RGoogleTrends, FlashMXML, SVGAnnotation</title>
		<link>http://yihui.name/en/2009/10/some-interesting-packages-in-r-swfdevice-rgoogletrends-flashmxml-svgannotation/</link>
		<comments>http://yihui.name/en/2009/10/some-interesting-packages-in-r-swfdevice-rgoogletrends-flashmxml-svgannotation/#comments</comments>
		<pubDate>Tue, 20 Oct 2009 02:25:57 +0000</pubDate>
		<dc:creator>Yihui Xie</dc:creator>
				<category><![CDATA[R Language]]></category>
		<category><![CDATA[Cameron Bracken]]></category>
		<category><![CDATA[Duncan Temple Lang]]></category>
		<category><![CDATA[Flash]]></category>
		<category><![CDATA[FlashMXML]]></category>
		<category><![CDATA[Google Trends]]></category>
		<category><![CDATA[Omegahat]]></category>
		<category><![CDATA[RGoogleTrends]]></category>
		<category><![CDATA[SVG]]></category>
		<category><![CDATA[SVGAnnotation]]></category>
		<category><![CDATA[swfDevice]]></category>

		<guid isPermaLink="false">http://yihui.name/en/?p=322</guid>
		<description><![CDATA[I love R because there are always exciting new packages which can be far beyond your imagination. Here I&#8217;d like to introduce a couple of packages that look really awesome:
1. swfDevice: R graphics device for SWF output (by Cameron Bracken)
This package is still at a pre-alpha stage but you can see a sketch now in [...]]]></description>
			<content:encoded><![CDATA[<p>I love R because there are always exciting new packages which can be far beyond your imagination. Here I&#8217;d like to introduce a couple of packages that look really awesome:</p>
<h1>1. <code>swfDevice</code>: R graphics device for SWF output (by Cameron Bracken)</h1>
<p>This package is still at a pre-alpha stage but you can see a sketch now in R-Forge:<a href="https://r-forge.r-project.org/projects/swfdevice/" target="_blank"> https://r-forge.r-project.org/projects/swfdevice/</a></p>
<p>Its author, Cameron, certainly knows well that I will be excited to see it, because I&#8217;ve been waiting for a long long time for the REAL Flash animation output in R. What I&#8217;ve done in my <code>animation</code> package is simply using SWF Tools to combine several &#8220;static&#8221; pictures (PNG or PDF, &#8230;) into a naive Flash animation &#8212; by &#8220;naive&#8221; I mean there is no interaction or real dynamic stuff in the Flash animation. Hopefully Cameron will provide a useful tool to create genuine Flash animations directly from R (with the help of the library <code>libming</code>).</p>
<p>By the way, I have to mention that the <code>tikzDevice</code> package by Cameron and another author is also fantastic for generating high-quality graphics LaTeX.<span id="more-322"></span></p>
<h1>2. <code>RGoogleTrends</code>: Query and download Google Trends data in R</h1>
<p>Ever heard of <a href="http://www.google.com/trends">Google Trends</a>? Duncan Temple Lang released an R package named &#8220;<a href="http://www.omegahat.org/RGoogleTrends">RGoogleTrends</a>&#8221; that allows you to download Google Trends data directly from R. Basically this package uses <code>RCurl</code> to log in your Google account and send queries to get Google Trends data. Well, you may ask &#8220;why bother using a package since I can manually download the data by myself?&#8221;; just imagine R can automatically and dynamically do it for you, so you don&#8217;t have to open the web page every day.</p>
<h1>3. <code>FlashMXML</code> and <code>SVGAnnotation</code>: New graphics devices for R</h1>
<p>They are also written by Duncan Temple Lang. <code>FlashMXML</code> can record R graphics in MXML (a kind of XML language) and we can compile the XML file to Flash output. <code>SVGAnnotation</code> enables us to save R graphics in SVG format, which also supports animation. The function <code>animate()</code> will be of great help to my <code>animation</code> package, I think.</p>
<p>You may check the Omegahat website for more interesting packages: <a href="http://www.omegahat.org">http://www.omegahat.org</a></p>
<h2  class="related_post_title">Related Posts</h2><ul class="related_post"><li><a href="http://yihui.name/en/2009/12/happy-new-year-with-r/" title="Happy New Year with R">Happy New Year with R</a></li><li><a href="http://yihui.name/en/2009/12/merry-christmas-using-r/" title="Merry Christmas Using R">Merry Christmas Using R</a></li><li><a href="http://yihui.name/en/2009/06/simulation-of-burning-fire-in-r/" title="Simulation of Burning Fire in R">Simulation of Burning Fire in R</a></li><li><a href="http://yihui.name/en/2009/06/creating-tag-cloud-using-r-and-flash-javascript-swfobject/" title="Creating Tag Cloud Using R and Flash / JavaScript (SWFObject)">Creating Tag Cloud Using R and Flash / JavaScript (SWFObject)</a></li><li><a href="http://yihui.name/en/2008/06/set-framerate-in-pdf2swf/" title="Set framerate in pdf2swf">Set framerate in pdf2swf</a></li></ul>]]></content:encoded>
			<wfw:commentRss>http://yihui.name/en/2009/10/some-interesting-packages-in-r-swfdevice-rgoogletrends-flashmxml-svgannotation/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>50000 Revisions Committed to R</title>
		<link>http://yihui.name/en/2009/10/50000-revisions-committed-to-r/</link>
		<comments>http://yihui.name/en/2009/10/50000-revisions-committed-to-r/#comments</comments>
		<pubDate>Sat, 10 Oct 2009 06:04:17 +0000</pubDate>
		<dc:creator>Yihui Xie</dc:creator>
				<category><![CDATA[Featured]]></category>
		<category><![CDATA[R Graphics]]></category>
		<category><![CDATA[R Language]]></category>
		<category><![CDATA[Animation]]></category>
		<category><![CDATA[Brian Ripley]]></category>
		<category><![CDATA[ggplot2]]></category>
		<category><![CDATA[Graphics]]></category>

		<guid isPermaLink="false">http://yihui.name/en/?p=304</guid>
		<description><![CDATA[oday Romain Francois posted an interesting topic in the R-help list, and you can read his blog post for more details: celebrating R commit #50000. 50000 is certainly not a small number; we do owe R core members a big &#8220;thank you&#8221; for their great efforts in this fantastic statistical language in the 13 years. [...]]]></description>
			<content:encoded><![CDATA[<a href="http://yihui.name/en/2009/10/50000-revisions-committed-to-r/"><span class="dropcap">T</span></a>oday <a rel="nofollow" href="http://romainfrancois.blog.free.fr/">Romain Francois</a> posted an interesting topic in the R-help list, and you can read his blog post for more details: <a title="celebrating R commit #50000" href="http://romainfrancois.blog.free.fr/index.php?post/2009/10/09/celebrating-R-commit-50000">celebrating R commit #50000</a>. 50000 is certainly not a small number; we do owe R core members a big &#8220;thank you&#8221; for their great efforts in this fantastic statistical language in the 13 years. When I saw Romain&#8217;s data, I suddenly remembered a question I asked to one of Prof Ripley&#8217;s student a couple of years ago: <em>does Prof Ripley ever sleep?</em> And he answered &#8220;No!&#8221;. No wonder we can see Prof Ripley so frequently in the R-help/devel mailing list. If you have stayed on R-help list for enough long time, you&#8217;ll surely know several facts, e.g. Martin Maechler will arrive in less than 3 minutes if you dare call an R package &#8220;library&#8221;, and you will get &#8220;Ripleyed&#8221; if you are not careful enough in posting your R code.</p>
<pre>&gt; library(fortunes)
&gt; fortune("Ripleyed")

And the fear of getting Ripleyed on the mailing list also makes me think, read,
and improve before submitting half baked questions to the list.
 -- Eric Kort
 R-help (January 2006)</pre>
<p><span id="more-304"></span>While these facts are revealing their great efforts in helping R users, we can see their work hours in committing revisions to R. For example, the answer to my question is clear in the graph below:</p>
<p><div id="attachment_306" class="wp-caption aligncenter" style="width: 490px"><a href="http://yihui.name/en/wp-content/uploads/2009/10/ripley-work-hour.png"><img class="size-full wp-image-306 " title="Prof Ripley Never Sleeps" src="http://yihui.name/en/wp-content/uploads/2009/10/ripley-work-hour.png" alt="Does Prof Ripley Ever Sleep?" width="480" height="480" /></a><p class="wp-caption-text">Prof Ripley Never Sleeps</p></div>
<pre>## R code borrowed from Romain Francios
process_chunk &lt;- function(txt) {
    if (length(txt) == 1L)
        return(NULL)
    header_line &lt;- strsplit(txt[2L], " | ", fixed = TRUE)[[1]][c(1L,
        2L, 3L)]
    revision &lt;- substring(header_line[1], 2)
    author &lt;- header_line[2]
    if (author %in% c("apache", "root"))
        return(NULL)
    date &lt;- substring(header_line[3], 1, 25)
    nlines &lt;- length(date)
    matrix(c(rep.int(revision, nlines), rep.int(author, nlines),
        rep.int(date, nlines)), nrow = nlines)
}
data &lt;- local({
    lines &lt;- readLines("rsvn.log")
    index &lt;- cumsum(grepl("^-+$", lines))
    commits &lt;- split(lines, index)
    do.call(rbind, lapply(commits, process_chunk))
})
colnames(data) &lt;- c("revision", "author", "date")
simple &lt;- data[!duplicated(data[, "revision"]), ]
hour.data = data.frame(author = simple[, "author"],
      hour = as.integer(substr(simple[, "date"], 12, 13)), year = as.integer(substr(simple[,
          "date"], 1, 4)))
hour.data = subset(hour.data, year &gt;= 1997 &amp; (author %in%
    c("hornik", "maechler", "pd", "ripley")))
library(ggplot2)
# png("ripley-work-hour.png")
qplot(hour, data = subset(hour.data, author == "ripley"),
    main = "Does Prof Ripley Ever Sleep?") + stat_bin(binwidth = 1)
# dev.off()</pre>
<p>Here I only selected four authors who have largest number of commits during 1997~2009. We can see the changes of working hours along these years:</p>
<div id="attachment_310" class="wp-caption aligncenter" style="width: 490px"><a href="http://yihui.name/en/wp-content/uploads/2009/10/r-core-work-hour.gif"><img class="size-full wp-image-310" title="Working hours of four R core members" src="http://yihui.name/en/wp-content/uploads/2009/10/r-core-work-hour.gif" alt="Working hours of four R core members" width="480" height="480" /></a><p class="wp-caption-text">Working hours of four R core members</p></div>
<pre>hour.max = max(with(hour.data, table(author, year,
    hour)))
library(animation)
# you need ImageMagick to create the GIF animation!
saveMovie({
for (i in sort(unique(hour.data$year))) {
    print(qplot(hour, data = subset(hour.data, year == i), xlim = c(0,
        23), ylim = c(0, hour.max), main = i) + facet_wrap(~author) +
        stat_bin(binwidth = 1))
}
}, interval = 1.5, moviename = "r-core-work-hour", outdir = getwd())</pre>
<p>The patterns are clear: Kurt does not like burning night oil; Martin tends to work very early in the morning (esp during 2000~2004); Peter always work at mid-night (highly centered around 12pm); and for Prof Ripley, he works round the clock but most in the morning (probably that&#8217;s when he begins to &#8220;Ripley&#8221; users? after that time, less people dare to report bugs so his work decays exponentially?)</p>
<h2  class="related_post_title">Related Posts</h2><ul class="related_post"><li><a href="http://yihui.name/en/2007/12/make-optical-illusions-in-r-graphics-system/" title="Make Optical Illusions in R Graphics System">Make Optical Illusions in R Graphics System</a></li><li><a href="http://yihui.name/en/2007/10/animations-in-survey-sampling/" title="Animations in Survey Sampling">Animations in Survey Sampling</a></li><li><a href="http://yihui.name/en/2009/12/happy-new-year-with-r/" title="Happy New Year with R">Happy New Year with R</a></li><li><a href="http://yihui.name/en/2009/12/merry-christmas-using-r/" title="Merry Christmas Using R">Merry Christmas Using R</a></li><li><a href="http://yihui.name/en/2009/11/create-animations-in-pdf-documents-using-r/" title="Create Animations in PDF Documents Using R">Create Animations in PDF Documents Using R</a></li></ul>]]></content:encoded>
			<wfw:commentRss>http://yihui.name/en/2009/10/50000-revisions-committed-to-r/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>How to Import MS Excel Data into R</title>
		<link>http://yihui.name/en/2009/09/how-to-import-ms-excel-data-into-r/</link>
		<comments>http://yihui.name/en/2009/09/how-to-import-ms-excel-data-into-r/#comments</comments>
		<pubDate>Sat, 26 Sep 2009 20:53:59 +0000</pubDate>
		<dc:creator>Yihui Xie</dc:creator>
				<category><![CDATA[Computer Science]]></category>
		<category><![CDATA[Featured]]></category>
		<category><![CDATA[R Programming]]></category>
		<category><![CDATA[CSV]]></category>
		<category><![CDATA[Data]]></category>
		<category><![CDATA[Excel]]></category>
		<category><![CDATA[Pure Text]]></category>
		<category><![CDATA[R Language]]></category>
		<category><![CDATA[read.csv()]]></category>
		<category><![CDATA[read.table()]]></category>
		<category><![CDATA[RODBC]]></category>

		<guid isPermaLink="false">http://yihui.name/en/?p=295</guid>
		<description><![CDATA[s Sir Francis Bacon said, &#8220;Histories make men wise; poets witty; the mathematics subtile; natural philosophy deep; moral grave; logic and rhetoric able to contend.&#8221; And Windows stupid.
He should have added the last sentence if he were a Windows user in this age.
1. Avoid Using M$ Excel
A lot of R users often ask this question: [...]]]></description>
			<content:encoded><![CDATA[<a href="http://yihui.name/en/2009/09/how-to-import-ms-excel-data-into-r/"><span class="dropcap-none">A</span></a>s Sir Francis Bacon said, &#8220;Histories make men wise; poets witty; the mathematics subtile; natural philosophy deep; moral grave; logic and rhetoric able to contend.&#8221; And Windows stupid.</p>
<p>He should have added the last sentence if he were a Windows user in this age.</p>
<h1>1. Avoid Using M$ Excel</h1>
<p>A lot of R users often ask this question: &#8220;How to import MS Excel data into R?&#8221; Well, my suggestion is, avoid using M$ Excel if you are a statistician (or going to be a statistician) because you just cannot imagine how messy Excel data can be: some cells might be merged, some are colored, some texts are bold, several data tables can be put everywhere (e.g. cell(1,1) to (10,4), and (17,3) to (25,9)), stupid bar plots and pie charts are inserted in the sheets, silly statistical procedures that are wrong forever&#8230; If you don&#8217;t trust my words (yes, I&#8217;m a nobody), just read the examples here: <a title="http://biostat.mc.vanderbilt.edu/twiki/bin/view/Main/ExcelProblems" href="http://biostat.mc.vanderbilt.edu/twiki/bin/view/Main/ExcelProblems" target="_blank">Problems with Excel</a> (collected by Prof Harrell).</p>
<p>I know there are reasons for you to continue using Excel. Your boss required you to do so; you don&#8217;t have time to learn more about various data formats; everybody is using Excel, and you don&#8217;t want to be so cool to use R; or if you finish your tasks <em>too</em> quickly and accurately, your boss will doubt whether you have really spent time on working, hence you will get less money paid (this is a REAL story for me &#8211; though I didn&#8217;t get less payment, I was indeed doubted when I used R); &#8230;<span id="more-295"></span></p>
<h1>2. Data as Pure Text</h1>
<p>A quick solution to the problem is to save your Excel data in a pure text format, e.g. CSV (comma-separated value) or tab-delimited. If you have ever thumbed through Dr Murrell&#8217;s book &#8220;Introduction to Data Technologies&#8221;, you probably know that the CSV format is NOT an Excel-specific format, although Windows users always find the Excel icon is associated with the <code>*.csv</code> files. Pure text is a ridiculously simple data format, but it&#8217;s amazing that there are still many people who do not know anything about it. The basic idea is to <strong>separate</strong> data <strong>columns</strong> with a delimiter (e.g. &#8220;,&#8221; or &#8220;;&#8221;) and <strong>rows</strong> with a usual line-break symbol (e.g. carriage-return, which can be different in Windows and Linux). In this case, we can identify all data values as we do in the spreadsheet. Here is an example with data in a spreadsheet:</p>
<p><div id="attachment_297" class="wp-caption aligncenter" style="width: 542px"><a href="http://yihui.name/en/wp-content/uploads/2009/09/iris-datagrid.png"><img class="size-full wp-image-297 " title="Data in the Spreadsheet" src="http://yihui.name/en/wp-content/uploads/2009/09/iris-datagrid.png" alt="Data in Grid Cells" width="532" height="226" /></a><p class="wp-caption-text">Data in the Spreadsheet</p></div>
<p>If we save this data as a CSV file, and open it with a pure text editor (e.g. Notepad), we will see:</p>
<pre>"","Sepal.Length","Sepal.Width","Petal.Length","Petal.Width","Species"
"1",5,3.2,1.2,0.2,"setosa"
"2",5.1,3.8,1.9,0.4,"setosa"
"3",5.1,3.3,1.7,0.5,"setosa"
"4",6.7,3.1,4.7,1.5,"versicolor"
"5",5.1,3.7,1.5,0.4,"setosa"
"6",5,3,1.6,0.2,"setosa"
"7",5.3,3.7,1.5,0.2,"setosa"
"8",5,3.4,1.6,0.4,"setosa"
"9",4.9,2.4,3.3,1,"versicolor"
"10",6.3,2.5,5,1.9,"virginica"</pre>
<p>Or save as tab-delimited text:</p>
<pre>""	"Sepal.Length"	"Sepal.Width"	"Petal.Length"	"Petal.Width"	"Species"
"1"	5	3.2	1.2	0.2	"setosa"
"2"	5.1	3.8	1.9	0.4	"setosa"
"3"	5.1	3.3	1.7	0.5	"setosa"
"4"	6.7	3.1	4.7	1.5	"versicolor"
"5"	5.1	3.7	1.5	0.4	"setosa"
"6"	5	3	1.6	0.2	"setosa"
"7"	5.3	3.7	1.5	0.2	"setosa"
"8"	5	3.4	1.6	0.4	"setosa"
"9"	4.9	2.4	3.3	1	"versicolor"
"10"	6.3	2.5	5	1.9	"virginica"</pre>
<p>Then use <code>read.table()</code> or <code>read.csv()</code> in R to read these pure text files (as <code>data.frame</code>s).</p>
<p>A hint for lazy users: you can also select all the data cells, copy it (into clipboard) and use <code>read.table("clipboard")</code> to get the data into R. In this case, what exists in your clipboard is the tab-delimited pure text.</p>
<h1>3. What If I Insist on Using Excel</h1>
<p>All right, you don&#8217;t bother to save the excel sheet into pure text and even don&#8217;t want to copy it into clipboard, then you can treat Excel files as databases, although they are indeed bad databases. You must guarantee that the data is &#8220;clean&#8221; and well-formatted, i.e. observations in each row and variables in each column (no merged cells, better no graphs). We can use the <code>RODBC</code> package to establish a connection to the Excel file, and execute <code>SQL</code> commands in the connection to make queries to data. Functions related to this task are <code>odbcConnectExcel()</code> or <code>odbcConnectExcel2007()</code> (again, Excel is stupid &#8212; they always change the standard in order that their products can be inconsistent). This is described in details in the manual R-data (&#8220;R Data Import/Export&#8221;).</p>
<p>As <code>*.xls</code> (or <code>*.xlsx</code>) is a binary format, never try to <code>read.table("*.xls")</code>. Meanwhile, <code>read.xls()</code> in the <strong><code>gdata</code></strong> package might be what you want if you are looking for the <code>read.*</code>-style R functions. [Thanks, Doug!]</p>
<p>In most cases, pure text format suffices to work, although it is ridiculously simple. Take a look at the &#8220;source code&#8221; and you will know everything. By the way, the extension of a file name is not that important: <code>*.csv</code> does not have to be a comma-separated text file, and <code>*.doc</code> can be something other than a Word document. It&#8217;s just a matter of convention. Again, open it and see what on earth is inside.</p>
<h2  class="related_post_title">Related Posts</h2><ul class="related_post"><li><a href="http://yihui.name/en/2010/02/press-enter-in-lyx-sweave-as-you-wish/" title="Press Enter in LyX Sweave as You Wish">Press Enter in LyX Sweave as You Wish</a></li><li><a href="http://yihui.name/en/2009/12/happy-new-year-with-r/" title="Happy New Year with R">Happy New Year with R</a></li><li><a href="http://yihui.name/en/2009/12/merry-christmas-using-r/" title="Merry Christmas Using R">Merry Christmas Using R</a></li><li><a href="http://yihui.name/en/2009/11/create-animations-in-pdf-documents-using-r/" title="Create Animations in PDF Documents Using R">Create Animations in PDF Documents Using R</a></li><li><a href="http://yihui.name/en/2009/10/50000-revisions-committed-to-r/" title="50000 Revisions Committed to R">50000 Revisions Committed to R</a></li></ul>]]></content:encoded>
			<wfw:commentRss>http://yihui.name/en/2009/09/how-to-import-ms-excel-data-into-r/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Formatting Decimals in Texts with R</title>
		<link>http://yihui.name/en/2009/08/formatting-decimals-in-texts-with-r/</link>
		<comments>http://yihui.name/en/2009/08/formatting-decimals-in-texts-with-r/#comments</comments>
		<pubDate>Mon, 31 Aug 2009 02:34:24 +0000</pubDate>
		<dc:creator>Yihui Xie</dc:creator>
				<category><![CDATA[R Programming]]></category>
		<category><![CDATA[Capital of Statistics]]></category>
		<category><![CDATA[formatC()]]></category>
		<category><![CDATA[gregexpr()]]></category>
		<category><![CDATA[Regular Expression]]></category>
		<category><![CDATA[round()]]></category>
		<category><![CDATA[sapply()]]></category>

		<guid isPermaLink="false">http://yihui.name/en/?p=285</guid>
		<description><![CDATA[anping Chen raised a question in the Chinese COS forum on the output of Eviews: how to (re)format the decimal coefficients in equations as text output? For example, we want to round the numbers in CC = 16.5547557654 + 0.0173022117998*PP + 0.216234040485 * PP(-1) + 0.810182697599 * (WP + WG) to the 3rd decimal places. [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://yihui.name/en/2009/08/formatting-decimals-in-texts-with-r/"><span class="dropcap-purple">Y</span></a>anping Chen raised a question in the <a href="http://cos.name/bbs/read.php?tid=16247" target="_blank">Chinese COS forum</a> on the output of Eviews: how to (re)format the decimal coefficients in equations as text output? For example, we want to round the numbers in <code>CC = 16.5547557654 + 0.0173022117998*PP + 0.216234040485 * PP(-1) + 0.810182697599 * (WP + WG)</code> to the 3rd decimal places. This can be simply done by regular expressions, as decimals always begin with a &#8220;<code>.</code>&#8221;. The basic steps are:</p>
<ol>
<li>find out where are the decimals in the character string;</li>
<li>format them;</li>
<li>replace the original decimals with formatted values;</li>
</ol>
<p>Given a character vector, we can format the decimals with the code below:<span id="more-285"></span></p>
<pre># x: equations; FUN: formatting function; ...: passed to FUN
coefFormat = function(x, FUN, ...) {
    sapply(x, function(s) {
        dig = sapply(gregexpr("\\.[0-9]+", s), function(m) {
            sapply(seq(along = m), function(i) {
                substr(s, m[i], m[i] + attr(m, "match.length")[i] - 1)
            })
        })
        for (j in {
            if (is.null(dim(dig)))
                NULL
            else 1:dim(dig)[1]
        }) {
            s = sub(dig[j, 1], substring(FUN(as.numeric(dig[j, 1]), ...),
                2), s, fixed = TRUE)
        }
        s
    })
}</pre>
<p>I used <code>sapply()</code> for 3 times to avoid explicit loops but consequently the code might be difficult to read. The critical part is the regular expression &#8220;<code>\\.[0-9]+</code>&#8221; which means one of more (controlled by &#8220;<code>+</code>&#8221; after &#8220;<code>[0-9]</code>&#8221;) digits (&#8220;<code>[0-9]</code>&#8221; or &#8220;<code>[:digit:]</code>&#8221;) after a decimal point &#8220;<code>.</code>&#8221;. As &#8220;<code>.</code>&#8221; is a <em>metacharacter</em> in regular expressions, we need to use a backslash before it, and again, &#8220;<code>\</code>&#8221; is a special character in R, so we need another backslash to denote a backslash. <img src='http://yihui.name/en/wp-content/plugins/tango-smilies/tango/face-angel.png' alt='o:-)' class='wp-smiley' /> </p>
<pre>x = readLines(zz &lt;- textConnection(
"CC = 16.5547557654 + 0.0173022117998 * PP + 0.216234040485 * PP(-1) + 0.810182697599 * (WP + WG)

II = 20.2782089394 + 0.150221823899 * PP + 0.61594357734 * PP(-1) - 0.157787636546 * KK

WP = 1.50029688603 + C(10) * XX + 0.146673821502 * XX(-1) + 0.130395687204 * AA
"))
close(zz)

writeLines(coefFormat(x, round, digits = 3))
#  CC = 16.555 + 0.017 * PP + 0.216 * PP(-1) + 0.81 * (WP + WG)
#
#  II = 20.278 + 0.15 * PP + 0.616 * PP(-1) - 0.158 * KK
#
#  WP = 1.5 + C(10) * XX + 0.147 * XX(-1) + 0.13 * AA
#
writeLines(coefFormat(x, formatC, digits = 3, format = "f"))
#  CC = 16.555 + 0.017 * PP + 0.216 * PP(-1) + 0.810 * (WP + WG)
#  
#  II = 20.278 + 0.150 * PP + 0.616 * PP(-1) - 0.158 * KK
#  
#  WP = 1.500 + C(10) * XX + 0.147 * XX(-1) + 0.130 * AA
#</pre>
<h2  class="related_post_title">Related Posts</h2><ul class="related_post"><li><a href="http://yihui.name/en/2009/06/simulation-of-burning-fire-in-r/" title="Simulation of Burning Fire in R">Simulation of Burning Fire in R</a></li><li><a href="http://yihui.name/en/2007/09/r-language-definition-file-for-highlight/" title="R Language Definition File for &#8220;Highlight&#8221;">R Language Definition File for &#8220;Highlight&#8221;</a></li></ul>]]></content:encoded>
			<wfw:commentRss>http://yihui.name/en/2009/08/formatting-decimals-in-texts-with-r/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Counterintuitive Results in Flipping Coins</title>
		<link>http://yihui.name/en/2009/08/counterintuitive-results-in-flipping-coins/</link>
		<comments>http://yihui.name/en/2009/08/counterintuitive-results-in-flipping-coins/#comments</comments>
		<pubDate>Sat, 29 Aug 2009 03:50:32 +0000</pubDate>
		<dc:creator>Yihui Xie</dc:creator>
				<category><![CDATA[R Computation]]></category>
		<category><![CDATA[Theories]]></category>
		<category><![CDATA[Coin]]></category>
		<category><![CDATA[Probability]]></category>

		<guid isPermaLink="false">http://yihui.name/en/?p=280</guid>
		<description><![CDATA[oin-flipping is a rather old topic in probability theory, so most of us think we know very well about it, however, the other day I saw a question about this old topic (in David Smith&#8217;s REvolution?) which was beyond me expectation: how many times do we need to flip the coin until we get a [...]]]></description>
			<content:encoded><![CDATA[<a href="http://yihui.name/en/2009/08/counterintuitive-results-in-flipping-coins/"><span class="dropcap-purple">C</span></a>oin-flipping is a rather old topic in probability theory, so most of us think we know very well about it, however, the other day I saw a question about this old topic (in David Smith&#8217;s REvolution?) which was beyond me expectation: how many times do we need to flip the coin until we get a sequence of <code>HTH</code> and <code>HTT</code> respectively? (For example, for the sequence HHTH, the number for HTH to appear is 4, and in THTHTT, the number for HTT is 6.)</p>
<p>It seems that the two results are equivalent, as H and T occurs with equal probability 0.5, so we naturally believe the average numbers of steps to HTH and HTT are the same, but the fact is not as we imagined.</p>
<pre>## smart guys use math formulae to solve the problem,
## but *lazy* guys like me use simulations with R
coin.seq = function(v) {
    x = NULL
    n = 0
    while (!identical(x, v)) {
        x = append(x[length(x) - 1:0], rbinom(1, 1, 0.5))
        n = n + 1
    }
    n
}
set.seed(919)
mean(htt &lt;- replicate(1e+05, coin.seq(c(1, 0, 0))))
# [1] 8.00304
mean(hth &lt;- replicate(1e+05, coin.seq(c(1, 0, 1))))
# [1] 10.0062

png("coin-htt-hth.png", height = 150, width = 500)
par(mar = c(3, 2.5, 0.1, 0), mgp = c(2, 0.8, 0))
boxplot(list(HTT = htt, HTH = hth), horizontal = T,
    xlab = "n", ylim = range(boxplot(list(HTT = htt, HTH = hth),
        plot = FALSE)$stats))
points(c(mean(htt), mean(hth)), 1:2, pch = 19)
dev.off()</pre>
<p>The answer is counterintuitive, isn&#8217;t it?</p>
<p><div id="attachment_282" class="wp-caption aligncenter" style="width: 510px"><a href="http://yihui.name/en/wp-content/uploads/2009/08/coin-htt-hth.png"><img class="size-full wp-image-282" title="Number of times needed to get HTT and HTH" src="http://yihui.name/en/wp-content/uploads/2009/08/coin-htt-hth.png" alt="Number of times needed to get HTT and HTH" width="500" height="150" /></a><p class="wp-caption-text">Number of times needed to get HTT and HTH (bold segments are for median; dots denote mean)</p></div>
<p>Well, mathematicians certainly do not like my solution (I guess they even hate such an imprecise approach). I hope some smart guys can give me some hints on working out the probability distribution and hence the expectation.</p>
<h2  class="related_post_title">Related Posts</h2><ul class="related_post"><li><a href="http://yihui.name/en/2008/09/eyeball-test-to-identify-an-unfair-coin/" title="&#8220;Eyeball Test&#8221; to Identify An Unfair Coin (or A False Record)">&#8220;Eyeball Test&#8221; to Identify An Unfair Coin (or A False Record)</a></li></ul>]]></content:encoded>
			<wfw:commentRss>http://yihui.name/en/2009/08/counterintuitive-results-in-flipping-coins/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Simulation of Burning Fire in R</title>
		<link>http://yihui.name/en/2009/06/simulation-of-burning-fire-in-r/</link>
		<comments>http://yihui.name/en/2009/06/simulation-of-burning-fire-in-r/#comments</comments>
		<pubDate>Fri, 12 Jun 2009 04:43:34 +0000</pubDate>
		<dc:creator>Yihui Xie</dc:creator>
				<category><![CDATA[R Graphics]]></category>
		<category><![CDATA[R Programming]]></category>
		<category><![CDATA[Animation]]></category>
		<category><![CDATA[Capital of Statistics]]></category>
		<category><![CDATA[Fire]]></category>
		<category><![CDATA[Flash]]></category>
		<category><![CDATA[heat.colors()]]></category>
		<category><![CDATA[image()]]></category>
		<category><![CDATA[Linlin Yan]]></category>
		<category><![CDATA[png2swf]]></category>
		<category><![CDATA[R Language]]></category>
		<category><![CDATA[saveSWF()]]></category>
		<category><![CDATA[Simulation]]></category>

		<guid isPermaLink="false">http://yihui.name/en/?p=267</guid>
		<description><![CDATA[inlin Yan posted a cool (hot?) simulation of burning fire with R in the COS forum yesterday, which was indeed a warm welcome. I&#8217;m not sure whether our forum members will be scared by the &#8220;fire&#8221; under the title &#8220;Welcome to COS Forum&#8221;.   The fire was mainly created by the function image() with [...]]]></description>
			<content:encoded><![CDATA[<a href="http://yihui.name/en/2009/06/simulation-of-burning-fire-in-r/"><span class="dropcap-purple">L</span></a>inlin Yan posted <a href="http://cos.name/en/topic/the-first-r-code-here" target="_blank">a cool (hot?) simulation of burning fire</a> with R in the <a title="Capital of Statistics" href="http://cos.name/en/" target="_blank">COS forum</a> yesterday, which was indeed a <em>warm</em> welcome. I&#8217;m not sure whether our forum members will be scared by the &#8220;fire&#8221; under the title &#8220;Welcome to COS Forum&#8221;. <img src='http://yihui.name/en/wp-content/plugins/tango-smilies/tango/face-smile-big.png' alt=':grin:' class='wp-smiley' />  The fire was mainly created by the function <code>image()</code> with carefully designed rows and columns in heated colors <code>heat.colors()</code>. Here is one of the pictures generated from his code:</p>
<p><div id="attachment_273" class="wp-caption aligncenter" style="width: 490px"><a href="http://yihui.name/en/wp-content/uploads/2009/06/simulation-of-burning-fire-in-r.png"><img class="size-full wp-image-273" style="border: 1px solid black;" title="Simulation of Burning Fire in R" src="http://yihui.name/en/wp-content/uploads/2009/06/simulation-of-burning-fire-in-r.png" alt="Simulation of Burning Fire in R" width="480" height="480" /></a><p class="wp-caption-text">Simulation of Burning Fire in R</p></div>
<p><span id="more-267"></span>And code here:</p>
<pre>Fire &lt;- function(row = 100, col = 100, time = 500, fade = 0.03) {
  fire &lt;- matrix(0, col, row);
  fire[,1] &lt;- runif(col);

  for (t in 1:time) {
    image(fire, col = rev(heat.colors(row)),
      axes = FALSE, main = "Welcome to COS Forum!");

    fire &lt;- (
      fire +
      cbind(fire[,1], fire[c(col,1:(col-1)), 1:(row - 1)]) +
      cbind(fire[,1], fire[                , 1:(row - 1)]) +
      cbind(fire[,1], fire[c(2:col,1)      , 1:(row - 1)])
      ) / 4;
    fire &lt;- cbind(fire[,1], (fire + fade / 5 - runif(1, max = fade))[,-1]);
    fire[fire &lt; 0] &lt;- 0;

    r &lt;- runif(1);
    if (r &lt; .1) fire[,1] &lt;- fire[,1][c(2:col, 1)];
    if (r &gt; .9) fire[,1] &lt;- fire[,1][c(col, 1:(col-1))];
  };
  NULL;
}</pre>
<p>The speed of drawing animation frames is rather slow in my computer, but it doesn&#8217;t matter since we can use the <code>animation</code> package (hey, you are advertising!) to save all the image frames and convert them to a single animation file.</p>
<pre>library(animation)
# set row=50 instead of the default 100 to let the fire burn to the ceiling
# make sure you have installed the SWF Tools and the command 'png2swf' can
#    be executed (with or w/o it installation path); see ?saveSWF
saveSWF(Fire(50), interval = 0.05, dev = "png", outdir = getwd(),
    para = list(mar = c(0, 0, 2, 0)))</pre>
<p style="text-align: center;"><object style="width: 480px; height: 480px;" classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" width="480" height="480" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0"><param name="quality" value="high" /><param name="wmode" value="transparent" /><param name="src" value="http://yihui.name/en/wp-content/uploads/2009/06/fire-with-r-by-yan-linlin.swf" /><embed style="width: 480px; height: 480px;" type="application/x-shockwave-flash" width="480" height="480" src="http://yihui.name/en/wp-content/uploads/2009/06/fire-with-r-by-yan-linlin.swf" wmode="transparent" quality="high"></embed></object></p>
<p>Now the animation is much more smooth than what we saw in R graphics window.</p>
<p>Thanks, awesome Linlin.</p>
<span class="attention">For those who are not familiar with the website &#8220;<a title="Capital of Statistics" href="http://cos.name/" target="_blank">Capital of Statistics</a>&#8221; (COS), I&#8217;d like to give a brief introduction here: this website was built 3 years ago by me and it was originally a Chinese website for discussion in statistics, but later I thought a place for English-speaking visitors was also necessary, so an English forum was constructed: <a title="Capital of Statistics" href="http://cos.name/en/" target="_blank">http://cos.name/en/</a>. Please feel free to join us if you are interested.</span>
<h2  class="related_post_title">Related Posts</h2><ul class="related_post"><li><a href="http://yihui.name/en/2009/12/happy-new-year-with-r/" title="Happy New Year with R">Happy New Year with R</a></li><li><a href="http://yihui.name/en/2009/12/merry-christmas-using-r/" title="Merry Christmas Using R">Merry Christmas Using R</a></li><li><a href="http://yihui.name/en/2009/11/create-animations-in-pdf-documents-using-r/" title="Create Animations in PDF Documents Using R">Create Animations in PDF Documents Using R</a></li><li><a href="http://yihui.name/en/2009/10/50000-revisions-committed-to-r/" title="50000 Revisions Committed to R">50000 Revisions Committed to R</a></li><li><a href="http://yihui.name/en/2009/06/creating-tag-cloud-using-r-and-flash-javascript-swfobject/" title="Creating Tag Cloud Using R and Flash / JavaScript (SWFObject)">Creating Tag Cloud Using R and Flash / JavaScript (SWFObject)</a></li></ul>]]></content:encoded>
			<wfw:commentRss>http://yihui.name/en/2009/06/simulation-of-burning-fire-in-r/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>
