<?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>Statistics, R, Graphics and Fun &#187; Capital of Statistics</title>
	<atom:link href="http://yihui.name/en/tag/capital-of-statistics/feed/" rel="self" type="application/rss+xml" />
	<link>http://yihui.name/en</link>
	<description>Yihui XIE</description>
	<lastBuildDate>Thu, 26 Aug 2010 03:32:16 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.1</generator>
		<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-blue">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>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 carefully designed [...]]]></description>
			<content:encoded><![CDATA[<a href="http://yihui.name/en/2009/06/simulation-of-burning-fire-in-r/"><span class="dropcap-brown">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/2010/03/a-demo-for-the-ratio-estimation/" title="A Demo for the Ratio Estimation in Sampling Survey (Animation)">A Demo for the Ratio Estimation in Sampling Survey (Animation)</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/06/simulation-of-burning-fire-in-r/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>
