Econometrics and Free Software2015-12-15T06:51:39+00:00http://b-rodrigues.github.comBruno Rodriguesbrodrigues@unistra.frBootstrapping standard errors for difference-in-differences estimation with R2015-11-11T00:00:00+00:00http://b-rodrigues.github.com/2015/11/11/bootstrapping-did-with-r
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<!-- MathJax scripts -->
<script type="text/javascript" src="https://c328740.ssl.cf1.rackcdn.com/mathjax/2.0-latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML">
</script>
</head>
<body>
<p>I’m currently working on a paper (with my colleague Vincent Vergnat who is also a Phd candidate at BETA) where I want to estimate the causal impact of the birth of a child on hourly and daily wages as well as yearly worked hours. For this we are using non-parametric difference-in-differences (henceforth DiD) and thus have to bootstrap the standard errors. In this post, I show how this is possible using the function <code>boot</code>.</p>
<p>For this we are going to replicate the example from Wooldridge’s <em>Econometric Analysis of Cross Section and Panel Data</em> and more specifically the example on page 415. You can download the data for R <a href="/assets/files/kielmc.RData">here</a>. The question we are going to try to answer is <em>how much does the price of housing decrease due to the presence of an incinerator in the neighborhood?</em></p>
<p>First put the data in a folder and set the correct working directory and load the <code>boot</code> library.</p>
<pre class="r"><code>library(boot)
setwd("/home/path/to/data/kiel data/")
load("kielmc.RData")</code></pre>
<p>Now you need to write a function that takes the data as an argument, as well as an indices argument. This argument is used by the <code>boot</code> function to select samples. This function should return the statistic you’re interested in, in our case, the DiD estimate.</p>
<pre class="r"><code>run_DiD <- function(my_data, indices){
d <- my_data[indices,]
return(
mean(d$rprice[d$year==1981 & d$nearinc==1]) -
mean(d$rprice[d$year==1981 & d$nearinc==0]) -
(mean(d$rprice[d$year==1978 & d$nearinc==1]) -
mean(d$rprice[d$year==1978 & d$nearinc==0]))
)
}</code></pre>
<p>You’re almost done! To bootstrap your DiD estimate you just need to use the boot function. If you have cpu with multiple cores (which you should, single core machines are quite outdated by now) you can even parallelize the bootstrapping.</p>
<pre class="r"><code>boot_est <- boot(data, run_DiD, R=1000, parallel="multicore", ncpus = 2)</code></pre>
<p>Now you should just take a look at your estimates:</p>
<pre class="r"><code>boot_est</code></pre>
<pre><code>##
## ORDINARY NONPARAMETRIC BOOTSTRAP
##
##
## Call:
## boot(data = data, statistic = run_DiD, R = 1000, parallel = "multicore",
## ncpus = 2)
##
##
## Bootstrap Statistics :
## original bias std. error
## t1* -11863.9 -553.3393 8580.435</code></pre>
<p>These results are very similar to the ones in the book, only the standard error is higher.</p>
<p>You can get confidence intervals like this:</p>
<pre class="r"><code>quantile(boot_est$t, c(0.025, 0.975))</code></pre>
<pre><code>## 2.5% 97.5%
## -30186.397 3456.133</code></pre>
<p>or a t-statistic:</p>
<pre class="r"><code>boot_est$t0/sd(boot_est$t)</code></pre>
<pre><code>## [1] -1.382669</code></pre>
<p>Or the density of the replications:</p>
<pre class="r"><code>plot(density(boot_est$t))</code></pre>
<div style="text-align:center;">
<img src="/assets/images/density_did.png" width="670" height="450" />
</div>
<p>Just as in the book, we find that the DiD estimate is not significant to the 5% level.</p>
<p>How many bootstrap estimates should you run? To answer this question, it might be interesting to take a look at the following graph:</p>
<pre class="r"><code>plot(boot_est$t, type="l")</code></pre>
<div style="text-align:center;">
<img src="/assets/images/sims_did.png" width="670" height="450" />
</div>
<p>What you see here are the different values our bootstrapped statistic takes at the different replication steps. 1000 replications might be overkill, as there doesn’t seem to be any convergence going on.</p>
</body>
Update to Introduction to programming econometrics with R2015-05-03T00:00:00+00:00http://b-rodrigues.github.com/2015/05/03/update-introduction-r-programming
<p>This semester I taught a course on applied econometrics with the R programming language. For this, I created a document that I gave to my students and shared online. This is the kind of document I would have liked to read when I first started using R. I already had some programming experience in C and Pascal but this is not necessarily the case for everyone that is confronted to R when they start learning about econometrics.</p>
<p>This is why the beginning of the document focuses more on general programming knowledge and techniques, and then only on econometrics. People online seemed to like the document, as I’ve received some positive comments by David Smith from Revolution R (read his blog post about the document <a href="http://blog.revolutionanalytics.com/2015/01/introduction-to-applied-econometrics-with-r.html">here</a>) and Dave Giles which links to David’s blog post <a href="http://davegiles.blogspot.fr/2015/04/introduction-to-applied-econometrics.html?spref=tw">here</a>. People on twitter have also retweeted David’s and Dave’s tweets to their blog posts and I’ve received some requests by people to send them the PDF by email (because they live in places where Dropbox is not accessible unfortunately).</p>
<p>The document is still a work in progress (and will probably remain so for a long time), but I’ve added some new sections about reproducible research and thought that this update could warrant a new blog post.</p>
<p>For now, only linear models are reviewed, but I think I’ll start adding some chapters about non-linear models soonish. The goal for these notes, however, is not to re-invent the wheel: there are lots of good books about econometrics with R out there and packages that estimate a very wide range of models. What I want for these notes, is to focus more on the programming knowledge an econometrician needs, in a very broad and general sense. I want my students to understand that R is a true programming language, and that they need to use every feature offered by such a language, and not think of R as a black box into which you only type pre-programmed commands, but also be able to program their own routines.</p>
<p>Also, I’ve made it possible to create the PDF using a Makefile. This may be useful for people that do not have access to Dropbox, but are familiar with git.</p>
<p>You can compile the book in two ways: first download the whole repository:</p>
<p><code>git clone git@bitbucket.org:b-rodrigues/programmingeconometrics.git</code></p>
<p>and then, with Rstudio, open the file <em>appliedEconometrics.Rnw</em> and knit it. Another solution is to use the Makefile. Just type:</p>
<p><code>make</code></p>
<p>inside a terminal (should work on GNU+Linux and OSX systems) and it should compile the document. You may get some message about “additional information” for some R packages. When these come up, just press Q on your keyboard to continue the compilation process.</p>
<p>Get the notes here: <a href="https://www.dropbox.com/s/k0tfyqlf3uxz6m2/Introduction%20to%20programming%20Econometrics%20with%20R%20-%20Draft.pdf?dl=0">download</a></p>
<p>As always, if you have questions or suggestions, do not hesitate to send me an email: <a href="mailto:brodrigues@unistra.fr">brodrigues@unistra.fr</a> and I sure hope you’ll find these notes useful!</p>
Export R output to a file2015-02-22T00:00:00+00:00http://b-rodrigues.github.com/2015/02/22/export-r-output-to-file
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<!-- MathJax scripts -->
<script type="text/javascript" src="https://c328740.ssl.cf1.rackcdn.com/mathjax/2.0-latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML">
</script>
</head>
<body>
<p>Sometimes it is useful to export the output of a long-running R command. For example, you might want to run a time consuming regression just before leaving work on Friday night, but would like to get the output saved inside your Dropbox folder to take a look at the results before going back to work on Monday.</p>
<p>This can be achieved very easily using <code>capture.output()</code> and <code>cat()</code> like so:</p>
<pre><code>out <- capture.output(summary(my_very_time_consuming_regression))
cat("My title", out, file="summary_of_my_very_time_consuming_regression.txt", sep="\n", append=TRUE)</code></pre>
<p><code>my_very_time_consuming_regression</code> is an object of class <code>lm</code> for example. I save the output of <code>summary(my_very_time_consuming_regression)</code> as text using <code>capture.output</code> and save it in a variable called <code>out</code>. Finally, I save <code>out</code> to a file called <code>summary_of_my_very_time_consuming_regression.txt</code> with the first sentence being <code>My title</code> (you can put anything there). The file <code>summary_of_my_very_time_consuming_regression.txt</code> doesn’t have to already exist in your working directory. The option <code>sep="\n"</code> is important or else the whole output will be written in a single line. Finally, <code>append=TRUE</code> makes sure your file won’t be overwritten; additional output will be appended to the file, which can be nice if you want to compare different versions of your model.</p>
</body>
Introduction to programming econometrics with R2015-01-12T00:00:00+00:00http://b-rodrigues.github.com/2015/01/12/introduction-to-programming-econometrics-with-r
<p>This semester, I’ll be teaching an introduction to applied econometrics with R, so I’ve decided to write a very small book called “Introduction to programming Econometrics with R”. This is primarily intended for bachelor students and the focus is not much on econometric theory, but more on how to implement econometric theory into computer code, using the R programming language. It’s very basic and doesn’t cover any advanced topics in econometrics and is intended for people with 0 previous programming knowledge. It is still very rough around the edges, and it’s missing the last chapter about reproducible research, and the references, but I think it’s time to put it out there; someone else than my students may find it useful. The book’s probably full of typos and mistakes, so don’t hesitate to drop me an e-mail if you find something fishy: brodrigues@unistra.fr</p>
<p>Also there might be some sections at the beginning that only concern my students. Just ignore that.</p>
<p>Get it here: <a href="https://www.dropbox.com/s/k0tfyqlf3uxz6m2/Introduction%20to%20programming%20Econometrics%20with%20R%20-%20Draft.pdf?dl=0">download</a></p>
R, R with Atlas, R with OpenBLAS and Revolution R Open: which is fastest?2014-11-11T00:00:00+00:00http://b-rodrigues.github.com/2014/11/11/benchmarks-r-blas-atlas-rro
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<!-- MathJax scripts -->
<script type="text/javascript" src="https://c328740.ssl.cf1.rackcdn.com/mathjax/2.0-latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML">
</script>
</head>
<body>
<p>In this short post, I benchmark different “versions” of R. I compare the execution speeds of R, R linked against OpenBLAS, R linked against ATLAS and Revolution R Open. Revolution R Open is a new open source version of R made by Revolution Analytics. It is linked against MKL and should offer huge speed improvements over vanilla R. Also, it uses every cores of your computer by default, without any change whatsoever to your code.</p>
<p>TL;DR: Revolution R Open is the fastest of all the benchmarked versions (with R linked against OpenBLAS and ATLAS just behind), and easier to setup. </p>
<h2>Setup</h2>
<p>I benchmarked these different versions of R using <code>R-benchmark-25.R</code> that you can download <a href="http://r.research.att.com/benchmarks/R-benchmark-25.R">here</a>. This benchmark file was created by Simon Urbanek.</p>
<p>I ran the benchmarks on my OpenSUSE 13.2 computer with a Pentium Dual-Core CPU E6500@2.93GHz with 4GB of Ram. It's outdated, but it's still quite fast for most of my numerical computation needs. I installed “vanilla” R from the official OpenSUSE repositories which is currently at version 3.1.2.</p>
<p>Then, I downloaded OpenBLAS and ATLAS also from the official OpenSUSE repositories and made R use these libraries instead of its own implementation of BLAS. The way I did that is a bit hacky, but works: first, go to <code>/usr/lib64/R/lib</code> and backup <code>libRblas.so</code> (rename it to <code>libRblas.soBackup</code> for instance). Then link <code>/usr/lib64/libopenblas.so.0</code> to <code>/usr/lib64/R/lib/libRblas</code>, and that's it, R will use OpenBLAS. For ATLAS, you can do it in the same fashion, but you'll find the library in <code>/usr/lib64/atlas/</code>. These paths should be the same for any GNU/Linux distribution. For other operating systems, I'm sure you can find where these libraries are with Google.</p>
<p>The last version I benchmarked was Revolution R Open. This is a new version of R released by Revolution Analytics. Revolution Analytics had their own version of R, called Revolution R, for quite some time now. They decided to release a completely free as in freedom and free as in free beer version of this product which they now renamed Revolution R Open. You can download Revolution R Open <a href="http://mran.revolutionanalytics.com/download/#review">here</a>. You can have both “vanilla” R and Revolution R Open installed on your system. </p>
<h2>Results</h2>
<p>I ran the <code>R-benchmark-25.R</code> 6 times for every version but will only discuss the 4 best runs.</p>
<style type="text/css">
.tg {border-collapse:collapse;border-spacing:0;}
.tg td{font-family:Arial, sans-serif;font-size:14px;padding:10px 11px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;}
.tg th{font-family:Arial, sans-serif;font-size:14px;font-weight:normal;padding:10px 11px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;}
.tg .tg-0ord{text-align:right}
</style>
<table class="tg">
<tr>
<th class="tg-031e">R version</th>
<th class="tg-0ord">Fastest run</th>
<th class="tg-0ord">Slowest run</th>
<th class="tg-0ord">Mean Run</th>
</tr>
<tr>
<td class="tg-031e">Vanilla R</td>
<td class="tg-0ord">63.65</td>
<td class="tg-0ord">66.21</td>
<td class="tg-0ord">64.61</td>
</tr>
<tr>
<td class="tg-031e">OpenBLAS R</td>
<td class="tg-0ord">15.63</td>
<td class="tg-0ord">18.96</td>
<td class="tg-0ord">16.94</td>
</tr>
<tr>
<td class="tg-031e">ATLAS R</td>
<td class="tg-0ord">16.92</td>
<td class="tg-0ord">21.57</td>
<td class="tg-0ord">18.24</td>
</tr>
<tr>
<td class="tg-031e">RRO</td>
<td class="tg-0ord">14.96</td>
<td class="tg-0ord">16.08</td>
<td class="tg-0ord">15.49</td>
</tr>
</table>
<p>As you can read from the table above, Revolution R Open was the fastest of the four versions, but not significantly faster than BLAS or ATLAS R. However, RRO uses all the available cores by default, so if your code relies on a lot matrix algebra, RRO might be actually a lot more faster than OpenBLAS and ATLAS R. Another advantage of RRO is that it is very easy to install, and also works with Rstudio and is compatible with every R package to existence. "Vanilla" R is much slower than the other three versions, more than 3 times as slow! </p>
<h2>Conclusion</h2>
<p>With other benchmarks, you could get other results, but I don't think that "vanilla" R could beat any of the other three versions. Whatever your choice, I recommend not using plain, “vanilla” R. The other options are much faster than standard R, and don't require much work to set up. I'd personally recommend Revolution R Open, as it is free software and compatible with CRAN packages and Rstudio. </p>
</body>
Object Oriented Programming with R: An example with a Cournot duopoly2014-04-23T00:00:00+00:00http://b-rodrigues.github.com/2014/04/23/r-s4-rootfinding
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<!-- MathJax scripts -->
<script type="text/javascript" src="https://c328740.ssl.cf1.rackcdn.com/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML">
</script>
</head>
<body>
<p>I started reading <em>Applied Computational Economics & Finance</em> by Mario J. Miranda and Paul L. Fackler. It is a very interesting book that I recommend to every one of my colleagues. The only issue I have with this book, is that the programming language they use is Matlab, which is proprietary. While there is a free as in freedom implementation of the Matlab language, namely Octave, I still prefer using R. In this post, I will illustrate one example the authors present in the book with R, using the package <code>rootSolve</code>. <code>rootSolve</code> implements Newtonian algorithms to find roots of functions; to specify the functions for which I want the roots, I use R's Object-Oriented Programming (OOP) capabilities to build a model that returns two functions. This is optional, but I found that it was a good example to illustrate OOP, even though simpler solutions exist, one of which was proposed by reddit user TheDrownedKraken (whom I thank) and will be presented at the end of the article.</p>
<h3>Theoretical background</h3>
<p>The example is taken from Miranda's and Fackler's book, on page 35. The authors present a Cournot duopoly model. In a Cournot duopoly model, two firms compete against each other by quantities. Both produce a certain quantity of an homogenous good, and take the quantity produce by their rival as given. </p>
<p>The inverse demand of the good is :</p>
<img src="http://latex.codecogs.com/png.latex?P(q) = q^{-\dfrac{1}{\eta}" alt="P(q) = q^{-\dfrac{1}{\eta}" />
<p>the cost function for firm i is:</p>
<img src="http://latex.codecogs.com/png.latex?C_i(q_i) = P(q_1+q_2)*q_i - C_i(q_i)" alt="C_i(q_i) = P(q_1+q_2)*q_i - C_i(q_i)}" />
<p>and the profit for firm i:</p>
<img src="http://latex.codecogs.com/png.latex?\pi_i(q1,q2) = P(q_1+q_2)q_i - C_i(q_i)" alt="\pi_i(q1,q2) = P(q_1+q_2)q_i - C_i(q_i)" />
<p>The optimality condition for firm i is thus:</p>
<img src="http://latex.codecogs.com/png.latex?\dfrac{\partial \pi_i}{\partial q_i} = (q1+q2)^{-\dfrac{1}{\eta}} - \dfrac{1}{\eta} (q_1+q_2)^{\dfrac{-1}{\eta-1}}q_i - c_iq_i=0." alt="\dfrac{\partial \pi_i}{\partial q_i} = (q1+q2)^{-\dfrac{1}{\eta}} - \dfrac{1}{\eta} (q_1+q_2)^{\dfrac{-1}{\eta-1}}q_i - c_iq_i=0." />
<h3>Implementation in R</h3>
<p>If we want to find the optimal quantities <img src="http://latex.codecogs.com/png.latex?\inline q_1" alt="\inline q_1" /> and <img src="http://latex.codecogs.com/png.latex?\inline q_2" alt="\inline q_2" /> we need to program the optimality condition and we could also use the jacobian of the optimality condition. The jacobian is generally useful to speed up the root finding routines. This is were OOP is useful. Firt let's create a new class, called <em>Model</em>:</p>
<pre><code class="r">setClass(Class = "Model", slots = list(OptimCond = "function", JacobiOptimCond = "function"))
</code></pre>
<p>This new class has two <em>slots</em>, which here are functions (in general <em>slots</em> are properties of your class); we need the model to return the optimality condition and the jacobian of the optimality condition.</p>
<p>Now we can create a function which will return these two functions for certain values of the parameters, <em>c</em> and <img src="http://latex.codecogs.com/png.latex?\inline \eta" alt="\inline \eta" /> of the model:</p>
<pre><code class="r">my_mod <- function(eta, c) {
e = -1/eta
OptimCond <- function(q) {
return(sum(q)^e + e * sum(q)^(e - 1) * q - diag(c) %*% q)
}
JacobiOptimCond <- function(q) {
return((e * sum(q)^e) * array(1, c(2, 2)) + (e * sum(q)^(e - 1)) * diag(1,
2) + (e - 1) * e * sum(q)^(e - 2) * q * c(1, 1) - diag(c))
}
return(new("Model", OptimCond = OptimCond, JacobiOptimCond = JacobiOptimCond))
}
</code></pre>
<p>The function <code>my_mod</code> takes two parameters, <code>eta</code> and <code>c</code> and returns two functions, the optimality condition and the jacobian of the optimality condition. Both are now accessible via <code>my_mod(eta=1.6,c = c(0.6,0.8))@OptimCond</code> and <code>my_mod(eta=1.6,c = c(0.6,0.8))@JacobiOptimCond</code> respectively (and by specifying values for <code>eta</code> and <code>c</code>).</p>
<p>Now, we can use the <code>rootSolve</code> package to get the optimal values <img src="http://latex.codecogs.com/png.latex?\inline q_1" alt="\inline q_1" /> and <img src="http://latex.codecogs.com/png.latex?\inline q_2" alt="\inline q_2" /> :</p>
<pre><code class="r">library("rootSolve")
multiroot(f = my_mod(eta = 1.6, c = c(0.6, 0.8))@OptimCond, start = c(1, 1),
maxiter = 100, jacfunc = my_mod(eta = 1.6, c = c(0.6, 0.8))@JacobiOptimCond)
</code></pre>
<pre><code>## $root
## [1] 0.8396 0.6888
##
## $f.root
## [,1]
## [1,] -2.220e-09
## [2,] 9.928e-09
##
## $iter
## [1] 4
##
## $estim.precis
## [1] 6.074e-09
</code></pre>
<p>After 4 iterations, we get that <img src="http://latex.codecogs.com/png.latex?\inline q_1" alt="\inline q_1" /> and <img src="http://latex.codecogs.com/png.latex?\inline q_2" alt="\inline q_2" /> are equal to 0.84 and 0.69 respectively, which are the same values as in the book!</p>
<h3>Suggestion by Reddit user, TheDrownedKraken</h3>
<p>I posted this article on rstats subbreddit on <a href="http://www.reddit.com">www.reddit.com</a>. I got a very useful comment by reddit member TheDrownedKraken which suggested the following approach, which doesn't need a new class to be build. I thank him for this. Here is his suggestion:</p>
<pre><code class="r">generator <- function(eta, a) {
e = -1/eta
OptimCond <- function(q) {
return(sum(q)^e + e * sum(q)^(e - 1) * q - diag(a) %*% q)
}
JacobiOptimCond <- function(q) {
return((e * sum(q)^e) * array(1, c(2, 2)) + (e * sum(q)^(e - 1)) * diag(1,
2) + (e - 1) * e * sum(q)^(e - 2) * q * c(1, 1) - diag(a))
}
return(list(OptimCond = OptimCond, JacobiOptimCond = JacobiOptimCond))
}
f.s <- generator(eta = 1.6, a = c(0.6, 0.8))
multiroot(f = f.s$OptimCond, start = c(1, 1), maxiter = 100, jacfunc = f.s$JacobiOptimCond)
</code></pre>
<pre><code>## $root
## [1] 0.8396 0.6888
##
## $f.root
## [,1]
## [1,] -2.220e-09
## [2,] 9.928e-09
##
## $iter
## [1] 4
##
## $estim.precis
## [1] 6.074e-09
</code></pre>
</body>
Using R as a Computer Algebra System with Ryacas2013-12-31T00:00:00+00:00http://b-rodrigues.github.com/2013/12/31/r-cas
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<!-- MathJax scripts -->
<script type="text/javascript" src="https://c328740.ssl.cf1.rackcdn.com/mathjax/2.0-latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML">
</script>
</head>
<body>
<p>R is used to perform statistical analysis and doesn't focus on symbolic maths. But it is sometimes useful to let the computer derive a function for you (and have the analytic expression of said derivative), but maybe you don't want to leave your comfy R shell. It is possible to turn R into a full-fledged computer algebra system. CASs are tools that perform symbolic operations, such as getting the expression of the derivative of a user-defined (and thus completely arbitrary) function. Popular CASs include the proprietary Mathematica and Maple. There exists a lot of CASs under a Free Software license, Maxima (based on the very old Macsyma), Yacas, Xcas… In this post I will focus on Yacas and the <code>Ryacas</code> libarary. There is also the possibility to use the <code>rSympy</code> library that uses the <code>Sympy</code> Python library, which has a lot more features than Yacas. However, depending on your operating system installation can be tricky as it also requires <code>rJava</code> as a dependency. </p>
<p>Even though <code>Ryacas</code> is quite nice to have, there are some issues though. For example, let's say you want the first derivative of a certain function f. If you use <code>Ryacas</code> to get it, the returned object won't be a function. There is a way to “extract” the text from the returned object and make a function out of it. But there are still other issues; I'll discuss them later.</p>
<h2>Installation</h2>
<p>Installation should be rather painless. On Linux you need to install Yacas first, which should be available in the major distros' repositories. Then you can install <code>Ryacas</code> from within the R shell. On Windows, you need to run these three commands (don't bother installing Yacas first):</p>
<pre><code>install.packages('Ryacas')
library(Ryacas)
yacasInstall()
</code></pre>
<p>You can find more information on the <a href="https://code.google.com/p/ryacas/#INSTALLATION">project's page</a>.</p>
<h2>Example session</h2>
<p>First, you must load <code>Ryacas</code> and define symbols that you will use in your functions.</p>
<pre><code class="r">require("Ryacas")
</code></pre>
<pre><code>## Loading required package: Ryacas Loading required package: XML
</code></pre>
<pre><code class="r">x <- Sym("x")
</code></pre>
<p>You can then define your fonctions:</p>
<pre><code class="r">my_func <- function(x) {
return(x/(x^2 + 3))
}
</code></pre>
<p>And you can get the derivative for instance:</p>
<pre><code class="r">my_deriv <- yacas(deriv(my_func(x), x))
</code></pre>
<pre><code>## [1] "Starting Yacas!"
</code></pre>
<p>If you check the class of <code>my_deriv</code>, you'll see that it is of class <code>yacas</code>, which is not very useful. Let's «convert» it to a function:</p>
<pre><code class="r">my_deriv2 <- function(x) {
eval(parse(text = my_deriv$YacasForm))
}
</code></pre>
<p>We can then evaluate it. A lot of different operations are possible. But there are some problems.</p>
<h2>Issues with Ryacas</h2>
<p>You can't use elements of a vector as parameters of your function, i.e.:</p>
<pre><code class="r">theta <- Sym("theta")
func <- function(x) {
return(theta[1] * x + theta[2])
}
# Let's integrate this
Func <- yacas(Integrate(func(x), x))
</code></pre>
<p>returns <code>(x^2*theta)/2+NA*x;</code> which is not quite what we want…there is a workaround however. Define your functions like this:</p>
<pre><code class="r">a <- Sym("a")
b <- Sym("b")
func2 <- function(x) {
return(a * x + b)
}
# Let's integrate this
Func2 <- yacas(Integrate(func2(x), x))
</code></pre>
<p>we get the expected result: <code>(x^2*a)/2+b*x;</code>. Now replace <code>a</code> and <code>b</code> by the thetas:</p>
<pre><code class="r">Func2 <- gsub("a", "theta[1]", Func2$YacasForm)
Func2 <- gsub("b", "theta[2]", Func2)
</code></pre>
<p>Now we have what we want: </p>
<pre><code class="r">Func2
</code></pre>
<pre><code>## [1] "(x^2*theta[1])/2+theta[2]*x;"
</code></pre>
<p>You can then copy-paste this result into a function.</p>
<p>Another problem is if you use built-in functions that are different between R and Yacas. For example:</p>
<pre><code class="r">my_log <- function(x) {
return(sin(log(2 + x)))
}
</code></pre>
<p>Now try to differentiate it:</p>
<pre><code class="r">dmy_log <- yacas(deriv(my_log(x), x))
</code></pre>
<p>you get: <code>Cos(Ln(x+2))/(x+2);</code>. The problem with this, is that R doesn't recognize <code>Cos</code> as the cosine (which is <code>cos</code> in R) and the same goes for <code>Ln</code>. These are valid Yacas functions, but that is not the case in R. So you'll have to use <code>gsub</code> to replace these functions and then copy paste the end result into a function.</p>
<h2>Conclusion</h2>
<p>While it has some flaws, <code>Ryacas</code> can be quite useful if you need to derive or integrate complicated expressions that you then want to use in R. Using some of the tricks I showed here, you should be able to overcome some of its shortcomings. If installation of <code>rJava</code> and thus <code>rSympy</code> becomes easier, I'll probably also do a short blog-post about it, as it has more features than <code>Ryacas</code>.</p>
</body>
Nonlinear Gmm with R - Example with a logistic regression2013-11-07T00:00:00+00:00http://b-rodrigues.github.com/2013/11/07/gmm-with-rmd
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<!-- MathJax scripts -->
<script type="text/javascript" src="https://c328740.ssl.cf1.rackcdn.com/mathjax/2.0-latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML">
</script>
</head>
<body>
<p>In this post, I will explain how you can use the R <code>gmm</code> package to estimate a non-linear model, and more specifically a logit model. For my research, I have to estimate Euler equations using the Generalized Method of Moments. I contacted Pierre Chaussé, the creator of the <code>gmm</code> library for help, since I was having some difficulties. I am very grateful for his help (without him, I'd still probably be trying to estimate my model!).</p>
<h3>Theoretical background, motivation and data set</h3>
<p>I will not dwell in the theory too much, because you can find everything you need <a href="https://en.wikipedia.org/wiki/Generalized_method_of_moments">here</a>. I think it's more interesting to try to understand why someone would use the Generalized Method of Moments instead of maximization of the log-likelihood. Well, in some cases, getting the log-likelihood can be quite complicated, as can be the case for arbitrary, non-linear models (for example if you want to estimate the parameters of a very non-linear utility function). Also, moment conditions can sometimes be readily available, so using GMM instead of MLE is trivial. And finally, GMM is... well, a very general method: every popular estimator can be obtained as a special case of the GMM estimator, which makes it quite useful.</p>
<p>Another question that I think is important to answer is: why this post? Well, because that's exactly the kind of post I would have loved to have found 2 months ago, when I was beginning to work with the GMM. Most posts I found presented the <code>gmm</code> package with very simple and trivial examples, which weren't very helpful. The example presented below is not very complicated per se, but much more closer to a real-world problem than most stuff that is out there. At least, I hope you will find it useful!</p>
<p>For illustration purposes, I'll use data from Marno Verbeek's <em>A guide to modern Econometrics</em>, used in the illustration on page 197. You can download the data from the book's companion page <a href="http://www.econ.kuleuven.ac.be/gme/">here</a> under the section <em>Data sets</em> or from the <code>Ecdat</code> package in R. I use the data set from Gretl though, as the dummy variables are numeric (instead of class <code>factor</code>) which makes life easier when writing your own functions. You can get the data set <a href="/assets/files/benefits.R">here</a>. </p>
<h3>Implementation in R</h3>
<p>I don't estimate the exact same model, but only use a subset of the variables available in the data set. Keep in mind that this post is just for illustration purposes.</p>
<p>First load the <code>gmm</code> package and load the data set:</p>
<pre><code class="r">require("gmm")
data <- read.table("path/to/data/benefits.R", header = T)
attach(data)
</code></pre>
<p>We can then estimate a logit model with the <code>glm()</code> function:</p>
<pre><code class="r">native <- glm(y ~ age + age2 + dkids + dykids + head + male + married + rr + rr2, family = binomial(link = "logit"), na.action = na.pass)
summary(native)
</code></pre>
<pre><code>##
## Call:
## glm(formula = y ~ age + age2 + dkids + dykids + head + male +
## married + rr + rr2, family = binomial(link = "logit"), na.action = na.pass)
##
## Deviance Residuals:
## Min 1Q Median 3Q Max
## -1.889 -1.379 0.788 0.896 1.237
##
## Coefficients:
## Estimate Std. Error z value Pr(>|z|)
## (Intercept) -1.00534 0.56330 -1.78 0.0743 .
## age 0.04909 0.02300 2.13 0.0328 *
## age2 -0.00308 0.00293 -1.05 0.2924
## dkids -0.10922 0.08374 -1.30 0.1921
## dykids 0.20355 0.09490 2.14 0.0320 *
## head -0.21534 0.07941 -2.71 0.0067 **
## male -0.05988 0.08456 -0.71 0.4788
## married 0.23354 0.07656 3.05 0.0023 **
## rr 3.48590 1.81789 1.92 0.0552 .
## rr2 -5.00129 2.27591 -2.20 0.0280 *
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## (Dispersion parameter for binomial family taken to be 1)
##
## Null deviance: 6086.1 on 4876 degrees of freedom
## Residual deviance: 5983.9 on 4867 degrees of freedom
## AIC: 6004
##
## Number of Fisher Scoring iterations: 4
</code></pre>
<p>Now comes the interesting part: how can you estimate such a non-linear model with the <code>gmm()</code> function from the <code>gmm</code> package? </p>
<p>For every estimation with the Generalized Method of Moments, you will need valid moment conditions. It turns out that in the case of the logit model, this moment condition is quite simple:</p>
$$
E[X' * (Y-\Lambda(X'\theta))] = 0
$$
<p>where \( \Lambda() \) is the logistic function. Let's translate this condition into code. First, we need the logistic function:</p>
<pre><code class="r">logistic <- function(theta, data) {
return(1/(1 + exp(-data %*% theta)))
}
</code></pre>
<p>and let's also define a new data frame, to make our life easier with the moment conditions (don't forget to add a column of ones to the matrix, hence the <code>1</code> after <code>y</code>):</p>
<pre><code class="r">dat <- data.matrix(cbind(y, 1, age, age2, dkids, dykids, head, male, married,
rr, rr2))
</code></pre>
<p>and now the moment condition itself:</p>
<pre><code class="r">moments <- function(theta, data) {
y <- as.numeric(data[, 1])
x <- data.matrix(data[, 2:11])
m <- x * as.vector((y - logistic(theta, x)))
return(cbind(m))
}
</code></pre>
<p>The moment condition(s) are given by a function which returns a matrix with as many columns as moment conditions (same number of columns as parameters for just-identified models).</p>
<p>To use the <code>gmm()</code> function to estimate our model, we need to specify some initial values to get the maximization routine going. One neat trick is simply to use the coefficients of a linear regression; I found it to work well in a lot of situations:</p>
<pre><code class="r">init <- (lm(y ~ age + age2 + dkids + dykids + head + male + married + rr + rr2))$coefficients
</code></pre>
<p>And finally, we have everything to use <code>gmm()</code>:</p>
<pre><code class="r">my_gmm <- gmm(moments, x = dat, t0 = init, type = "iterative", crit = 1e-25, wmatrix = "optimal", method = "Nelder-Mead", control = list(reltol = 1e-25, maxit = 20000))
summary(my_gmm)
</code></pre>
<pre><code>##
## Call:
## gmm(g = moments, x = dat, t0 = init, type = "iterative", wmatrix = "optimal",
## crit = 1e-25, method = "Nelder-Mead", control = list(reltol = 1e-25,
## maxit = 20000))
##
##
## Method: iterative
##
## Kernel: Quadratic Spectral
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) -0.9090571 0.5751429 -1.5805761 0.1139750
## age 0.0394254 0.0231964 1.6996369 0.0891992
## age2 -0.0018805 0.0029500 -0.6374640 0.5238227
## dkids -0.0994031 0.0842057 -1.1804799 0.2378094
## dykids 0.1923245 0.0950495 2.0234150 0.0430304
## head -0.2067669 0.0801624 -2.5793498 0.0098987
## male -0.0617586 0.0846334 -0.7297189 0.4655620
## married 0.2358055 0.0764071 3.0861736 0.0020275
## rr 3.7895781 1.8332559 2.0671300 0.0387219
## rr2 -5.2849002 2.2976075 -2.3001753 0.0214383
##
## J-Test: degrees of freedom is 0
## J-test P-value
## Test E(g)=0: 0.00099718345776501 *******
##
## #############
## Information related to the numerical optimization
## Convergence code = 10
## Function eval. = 17767
## Gradian eval. = NA
</code></pre>
<p>Please, notice the options <code>crit=1e-25,method="Nelder-Mead",control=list(reltol=1e-25,maxit=20000)</code>: these options mean that the Nelder-Mead algorithm is used, and to specify further options to the Nelder-Mead algorithm, the <code>control</code> option is used. This is very important, as Pierre Chaussé explained to me: non-linear optimization is an art, and most of the time the default options won't cut it and will give you false results. To add insult to injury, the Generalized Method of Moments itself is very capricious and you will also have to play around with different initial values to get good results. As you can see, the Convergence code equals 10, which is a code specific to the Nelder-Mead method which indicates «degeneracy of the Nelder–Mead simplex.» . I'm not sure if this is a bad thing though, but other methods can give you better results. I'd suggest you try always different maximization routines with different starting values to see if your estimations are robust. Here, the results are very similar to what we obtained with the built-in function <code>glm()</code> so we can stop here.</p>
<p>Should you notice any error whatsoever, do not hesitate to tell me.</p>
</body>
Method of Simulated Moments with R2013-01-29T00:00:00+00:00http://b-rodrigues.github.com/2013/01/29/method-of-simulated-moments-with-r
<p>Second update on my research, details <a href="/pages/Research.html">here</a>.</p>
Simulated Maximum Likelihood with R2013-01-16T00:00:00+00:00http://b-rodrigues.github.com/2013/01/16/simulated-maximum-likelihood-with-r
<p>First update on my research, details <a href="/pages/Research.html">here</a>.</p>
New website!2012-12-11T00:00:00+00:00http://b-rodrigues.github.com/2012/12/11/new-website
<p>This is my new website! It’s built using jekyll-bootstrap and hosted on Github.</p>