Econometrics and Free Software2016-08-18T07:12:59+00:00http://b-rodrigues.github.comBruno Rodriguescontact@brodrigues.coMerge a list of datasets together2016-07-30T00:00:00+00:00http://b-rodrigues.github.com/2016/07/30/merge-a-list-of-datasets-together
<p><a href="http://www.brodrigues.co/2016/07/26/read-a-lot-of-datasets-at-once-with-r">Last week</a> I showed how to read a lot of datasets at once with R, and this week I’ll continue from there and show a very simple function that uses this list of read datasets and merges them all together.</p>
<p>First we’ll use <code>read_list()</code> to read all the datasets at once (for more details read <a href="http://www.brodrigues.co/2016/07/26/read-a-lot-of-datasets-at-once-with-r">last week’s post</a>):</p>
<pre class="r"><code>library("readr")
library("tibble")
data_files <- list.files(pattern = ".csv")
print(data_files)</code></pre>
<pre><code>## [1] "data_1.csv" "data_2.csv" "data_3.csv"</code></pre>
<pre class="r"><code>list_of_data_sets <- read_list(data_files, read_csv)
glimpse(list_of_data_sets)</code></pre>
<pre><code>## List of 3
## $ data_1:Classes 'tbl_df', 'tbl' and 'data.frame': 19 obs. of 3 variables:
## ..$ col1: chr [1:19] "0,018930679" "0,8748013128" "0,1025635934" "0,6246140983" ...
## ..$ col2: chr [1:19] "0,0377725807" "0,5959457638" "0,4429121533" "0,558387159" ...
## ..$ col3: chr [1:19] "0,6241767189" "0,031324594" "0,2238059868" "0,2773350732" ...
## $ data_2:Classes 'tbl_df', 'tbl' and 'data.frame': 19 obs. of 3 variables:
## ..$ col1: chr [1:19] "0,9098418493" "0,1127788509" "0,5818891392" "0,1011773532" ...
## ..$ col2: chr [1:19] "0,7455905887" "0,4015039612" "0,6625796605" "0,029955339" ...
## ..$ col3: chr [1:19] "0,327232932" "0,2784035673" "0,8092386735" "0,1216045306" ...
## $ data_3:Classes 'tbl_df', 'tbl' and 'data.frame': 19 obs. of 3 variables:
## ..$ col1: chr [1:19] "0,9236124896" "0,6303271761" "0,6413583054" "0,5573887416" ...
## ..$ col2: chr [1:19] "0,2114708388" "0,6984538266" "0,0469865249" "0,9271510226" ...
## ..$ col3: chr [1:19] "0,4941919971" "0,7391538511" "0,3876723797" "0,2815014394" ...</code></pre>
<p>You see that all these datasets have the same column names. We can now merge them using this simple function:</p>
<pre class="r"><code>multi_join <- function(list_of_loaded_data, join_func, ...){
require("dplyr")
output <- Reduce(function(x, y) {join_func(x, y, ...)}, list_of_loaded_data)
return(output)
}</code></pre>
<p>This function uses <code>Reduce()</code>. <code>Reduce()</code> is a very important function that can be found in all functional programming languages. What does <code>Reduce()</code> do? Let’s take a look at the following example:</p>
<pre class="r"><code>Reduce(`+`, c(1, 2, 3, 4, 5))</code></pre>
<pre><code>## [1] 15</code></pre>
<p><code>Reduce()</code> has several arguments, but you need to specify at least two: a function, here <code>+</code> and a list, here <code>c(1, 2, 3, 4, 5)</code>. The next code block shows what <code>Reduce()</code> basically does:</p>
<pre><code>0 + c(1, 2, 3, 4, 5)
0 + 1 + c(2, 3, 4, 5)
0 + 1 + 2 + c(3, 4, 5)
0 + 1 + 2 + 3 + c(4, 5)
0 + 1 + 2 + 3 + 4 + c(5)
0 + 1 + 2 + 3 + 4 + 5</code></pre>
<p><code>0</code> had to be added as in “init”. You can also specify this “init” to <code>Reduce()</code>:</p>
<pre class="r"><code>Reduce(`+`, c(1, 2, 3, 4, 5), init = 20)</code></pre>
<pre><code>## [1] 35</code></pre>
<p>So what <code>multi_join()</code> does, is the same operation as in the example above, but where the function is a user supplied join or merge function, and the list of datasets is the one read with <code>read_list()</code>.</p>
<p>Let’s see what happens when we use <code>multi_join()</code> on our list:</p>
<pre class="r"><code>merged_data <- multi_join(list_of_data_sets, full_join)</code></pre>
<pre class="r"><code>class(merged_data)</code></pre>
<pre><code>## [1] "tbl_df" "tbl" "data.frame"</code></pre>
<pre class="r"><code>glimpse(merged_data)</code></pre>
<pre><code>## Observations: 57
## Variables: 3
## $ col1 <chr> "0,018930679", "0,8748013128", "0,1025635934", "0,6246140...
## $ col2 <chr> "0,0377725807", "0,5959457638", "0,4429121533", "0,558387...
## $ col3 <chr> "0,6241767189", "0,031324594", "0,2238059868", "0,2773350...</code></pre>
<p>You should make sure that all the data frames have the same column names but you can also join data frames with different column names if you give the argument <code>by</code> to the join function. This is possible thanks to <code>...</code> that allows you to pass further argument to <code>join_func()</code>.</p>
<p>This function was inspired by the one found on the blog <a href="http://novicemetrics.blogspot.lu/2011/04/merging-multiple-data-files-into-one.html">Coffee and Econometrics in the Morning</a>.</p>
Read a lot of datasets at once with R2016-07-26T00:00:00+00:00http://b-rodrigues.github.com/2016/07/26/read-a-lot-of-datasets-at-once-with-r
<p>I often have to read a lot of datasets at once using R. So I’ve wrote the following function to solve this issue:</p>
<pre class="r"><code>read_list <- function(list_of_datasets, read_func){
read_and_assign <- function(dataset, read_func){
dataset_name <- as.name(dataset)
dataset_name <- read_func(dataset)
}
# invisible is used to suppress the unneeded output
output <- invisible(
sapply(list_of_datasets,
read_and_assign, read_func = read_func, simplify = FALSE, USE.NAMES = TRUE))
# Remove the extension at the end of the data set names
names_of_datasets <- c(unlist(strsplit(list_of_datasets, "[.]"))[c(T, F)])
names(output) <- names_of_datasets
return(output)
}</code></pre>
<p>You need to supply a list of datasets as well as the function to read the datasets to <code>read_list</code>. So for example to read in <code>.csv</code> files, you could use <code>read.csv()</code> (or <code>read_csv()</code> from the <code>readr</code> package, which I prefer to use), or <code>read_dta()</code> from the package <code>haven</code> for STATA files, and so on.</p>
<p>Now imagine you have some data in your working directory. First start by saving the name of the datasets in a variable:</p>
<pre class="r"><code>data_files <- list.files(pattern = ".csv")
print(data_files)</code></pre>
<pre><code>## [1] "data_1.csv" "data_2.csv" "data_3.csv"</code></pre>
<p>Now you can read all the data sets and save them in a list with <code>read_list()</code>:</p>
<pre class="r"><code>library("readr")
library("tibble")
list_of_data_sets <- read_list(data_files, read_csv)
glimpse(list_of_data_sets)</code></pre>
<pre><code>## List of 3
## $ data_1:Classes 'tbl_df', 'tbl' and 'data.frame': 19 obs. of 3 variables:
## ..$ col1: chr [1:19] "0,018930679" "0,8748013128" "0,1025635934" "0,6246140983" ...
## ..$ col2: chr [1:19] "0,0377725807" "0,5959457638" "0,4429121533" "0,558387159" ...
## ..$ col3: chr [1:19] "0,6241767189" "0,031324594" "0,2238059868" "0,2773350732" ...
## $ data_2:Classes 'tbl_df', 'tbl' and 'data.frame': 19 obs. of 3 variables:
## ..$ col1: chr [1:19] "0,9098418493" "0,1127788509" "0,5818891392" "0,1011773532" ...
## ..$ col2: chr [1:19] "0,7455905887" "0,4015039612" "0,6625796605" "0,029955339" ...
## ..$ col3: chr [1:19] "0,327232932" "0,2784035673" "0,8092386735" "0,1216045306" ...
## $ data_3:Classes 'tbl_df', 'tbl' and 'data.frame': 19 obs. of 3 variables:
## ..$ col1: chr [1:19] "0,9236124896" "0,6303271761" "0,6413583054" "0,5573887416" ...
## ..$ col2: chr [1:19] "0,2114708388" "0,6984538266" "0,0469865249" "0,9271510226" ...
## ..$ col3: chr [1:19] "0,4941919971" "0,7391538511" "0,3876723797" "0,2815014394" ...</code></pre>
<p>If you prefer not to have the datasets in a list, but rather import them into the global environment, you can change the above function like so:</p>
<pre class="r"><code>read_list <- function(list_of_datasets, read_func){
read_and_assign <- function(dataset, read_func){
assign(dataset, read_func(dataset), envir = .GlobalEnv)
}
# invisible is used to suppress the unneeded output
output <- invisible(
sapply(list_of_datasets,
read_and_assign, read_func = read_func, simplify = FALSE, USE.NAMES = TRUE))
}</code></pre>
<p>But I personnally don’t like this second option, but I put it here for completeness.</p>
Data frame columns as arguments to dplyr functions2016-07-18T00:00:00+00:00http://b-rodrigues.github.com/2016/07/18/data-frame-columns-as-arguments-to-dplyr-functions
<p>Suppose that you would like to create a function which does a series of computations on a data frame. You would like to pass a column as this function’s argument. Something like:</p>
<pre class="r"><code>data(cars)
convertToKmh <- function(dataset, col_name){
dataset$col_name <- dataset$speed * 1.609344
return(dataset)
}</code></pre>
<p>This example is obviously not very interesting (you don’t need a function for this), but it will illustrate the point. You would like to append a column called <code>speed_in_kmh</code> with the speed in kilometers per hour to this dataset, but this is what happens:</p>
<pre class="r"><code>head(convertToKmh(cars, "speed_in_kmh"))</code></pre>
<pre><code>## speed dist col_name
## 1 4 2 6.437376
## 2 4 10 6.437376
## 3 7 4 11.265408
## 4 7 22 11.265408
## 5 8 16 12.874752
## 6 9 10 14.484096</code></pre>
<p>Your column is not called <code>speed_in_kmh</code> but <code>col_name</code>! It turns out that there is a very simple solution:</p>
<pre class="r"><code>convertToKmh <- function(dataset, col_name){
dataset[col_name] <- dataset$speed * 1.609344
return(dataset)
}
head(convertToKmh(cars, "speed_in_kmh"))</code></pre>
<pre><code>## speed dist speed_in_kmh
## 1 4 2 6.437376
## 2 4 10 6.437376
## 3 7 4 11.265408
## 4 7 22 11.265408
## 5 8 16 12.874752
## 6 9 10 14.484096</code></pre>
<p>You can access columns with <code>[]</code> instead of <code>$</code>.</p>
<p>But sometimes you want to do more complex things and for example have a function that groups by a variable and then computes new variables, filters by another and so on. You would like to avoid having to hard code these variables in your function, because then why write a function and of course you would like to use <code>dplyr</code> to do it.</p>
<p>I often use <code>dplyr</code> functions in my functions. For illustration purposes, consider this very simple function:</p>
<pre class="r"><code>simpleFunction <- function(dataset, col_name){
require("dplyr")
dataset %>%
group_by(col_name) %>%
summarise(mean_speed = mean(speed)) -> dataset
return(dataset)
}
simpleFunction(cars, "dist")</code></pre>
<p>This function takes a dataset as an argument, as well as a column name. However, this does not work. You get this error:</p>
<pre><code>Error: unknown variable to group by : col_name </code></pre>
<p>The variable <code>col_name</code> is passed to <code>simpleFunction()</code> as a string, but <code>group_by()</code> requires a variable name. So why not try to convert <code>col_name</code> to a name?</p>
<pre class="r"><code>simpleFunction <- function(dataset, col_name){
require("dplyr")
col_name <- as.name(col_name)
dataset %>%
group_by(col_name) %>%
summarise(mean_speed = mean(speed)) -> dataset
return(dataset)
}
simpleFunction(cars, "dist")</code></pre>
<p>You get the same error as before:</p>
<pre><code>Error: unknown variable to group by : col_name </code></pre>
<p>So how can you pass a column name to <code>group_by()</code>? Well, there is another version of <code>group_by()</code> called <code>group_by_()</code> that uses standard evaluation. You can learn more about it <a href="https://cran.r-project.org/web/packages/dplyr/vignettes/nse.html">here</a>. Let’s take a look at what happens when we use <code>group_by_()</code>:</p>
<pre class="r"><code>simpleFunction <- function(dataset, col_name){
require("dplyr")
dataset %>%
group_by_(col_name) %>%
summarise(mean_speed = mean(speed)) -> dataset
return(dataset)
}
simpleFunction(cars, "dist")</code></pre>
<pre><code>## # A tibble: 35 x 2
## dist mean_speed
## <dbl> <dbl>
## 1 2 4.0
## 2 4 7.0
## 3 10 6.5
## 4 14 12.0
## 5 16 8.0
## 6 17 11.0
## 7 18 10.0
## 8 20 13.5
## 9 22 7.0
## 10 24 12.0
## # ... with 25 more rows</code></pre>
<p>We can even use a formula instead of a string:</p>
<pre class="r"><code>simpleFunction(cars, ~dist)</code></pre>
<pre><code>## # A tibble: 35 x 2
## dist mean_speed
## <dbl> <dbl>
## 1 2 4.0
## 2 4 7.0
## 3 10 6.5
## 4 14 12.0
## 5 16 8.0
## 6 17 11.0
## 7 18 10.0
## 8 20 13.5
## 9 22 7.0
## 10 24 12.0
## # ... with 25 more rows</code></pre>
<p>What if you want to pass column names and constants, for example to filter without hardcoding anything?</p>
<p>Trying to do it naively will only yield pain and despair:</p>
<pre class="r"><code>simpleFunction <- function(dataset, col_name, value){
require("dplyr")
dataset %>%
filter_(col_name == value) %>%
summarise(mean_speed = mean(speed)) -> dataset
return(dataset)
}</code></pre>
<pre><code>> simpleFunction(cars, "dist", 10)
mean_speed
1 NaN
> simpleFunction(cars, dist, 10)
Error in col_name == value :
comparison (1) is possible only for atomic and list types
> simpleFunction(cars, ~dist, 10)
mean_speed
1 NaN
</code></pre>
<p>To solve this issue, we need to know a little bit about two concepts, <em>lazy evaluation</em> and <em>non-standard evaluation</em>. I recommend you read <a href="http://adv-r.had.co.nz/Computing-on-the-language.html">the following document</a> from Hadley Wickham’s book <em>Advanced R</em> as well as the part on lazy evaluation <a href="http://adv-r.had.co.nz/Functions.html#function-arguments">here</a>.</p>
<p>A nice package called <code>lazyeval</code> can help us out. We would like to make R understand that the column name is not <code>col_name</code> but the string inside it <code>"dist"</code>, and now we would like to use <code>filter()</code> for <code>dist</code> equal to <code>10</code>.</p>
<p>In the <code>lazyeval</code> package, you’ll find the function <code>interp()</code>. <code>interp()</code> allows you to</p>
<blockquote>
<p>build an expression up from a mixture of constants and variables.</p>
</blockquote>
<p>Take a look at this example:</p>
<pre class="r"><code>library(lazyeval)
interp(~x+y, x = 2)</code></pre>
<pre><code>## ~2 + y</code></pre>
<p>What you get back is this nice formula that you can then use within functions. To see why this is useful, let’s look at the above example again, and make it work using <code>interp()</code>:</p>
<pre class="r"><code>simpleFunction <- function(dataset, col_name, value){
require("dplyr")
require("lazyeval")
filter_criteria <- interp(~y == x, .values=list(y = as.name(col_name), x = value))
dataset %>%
filter_(filter_criteria) %>%
summarise(mean_speed = mean(speed)) -> dataset
return(dataset)
}
simpleFunction(cars, "dist", 10)</code></pre>
<pre><code>## mean_speed
## 1 6.5</code></pre>
<p>And now it works! For some reason, you have to pass the column name as a string though.</p>
<p>Sources: apart from the documents above, the following stackoverflow threads helped me out quite a lot: <a href="http://stackoverflow.com/questions/28973056/in-r-pass-column-name-as-argument-and-use-it-in-function-with-dplyrmutate-a">In R: pass column name as argument and use it in function with dplyr::mutate() and lazyeval::interp()</a> and <a href="http://stackoverflow.com/questions/26492280/non-standard-evaluation-nse-in-dplyrs-filter-pulling-data-from-mysql">Non-standard evaluation (NSE) in dplyr’s filter_ & pulling data from MySQL</a>.</p>
Careful with tryCatch2016-06-21T00:00:00+00:00http://b-rodrigues.github.com/2016/06/21/careful-with-trycatch
<p><code>tryCatch</code> is one of the functions that allows the users to handle errors in a simple way. With it, you can do things like: <code>if(error), then(do this)</code>.</p>
<p>Take the following example:</p>
<pre class="r"><code>sqrt("a")
Error in sqrt("a") : non-numeric argument to mathematical function</code></pre>
<p>Now maybe you’d want something to happen when such an error happens. You can achieve that with <code>tryCatch</code>:</p>
<pre class="r"><code>tryCatch(sqrt("a"), error=function(e) print("You can't take the square root of a character, silly!"))</code></pre>
<pre><code>## [1] "You can't take the square root of a character, silly!"</code></pre>
<p>Why am I interested in <code>tryCatch</code>?</p>
<p>I am currently working with dates, specifically birthdays of people in my data sets. For a given mother, the birthday of her child is given in three distinct columns: a column for the child’s birth year, birth month and birth day respectively. I’ve wanted to put everything in a single column and convert the birthday to unix time (I have a very good reason to do that, but I won’t bore you with the details).</p>
<p>Let’s create some data:</p>
<pre class="r"><code>mother <- as.data.frame(list(month=12, day=1, year=1988))</code></pre>
<p>In my data, there’s a lot more columns of course, such as the mother’s wage, education level, etc, but for illustration purposes, this is all that’s needed.</p>
<p>Now, to create this birthday column:</p>
<pre class="r"><code>mother$birth1 <- as.POSIXct(paste0(as.character(mother$year),
"-", as.character(mother$month),
"-", as.character(mother$day)),
origin="1970-01-01")</code></pre>
<p>and to convert it to unix time:</p>
<pre class="r"><code>mother$birth1 <- as.numeric(as.POSIXct(paste0(as.character(mother$year),
"-", as.character(mother$month),
"-", as.character(mother$day)),
origin="1970-01-01"))
print(mother)</code></pre>
<pre><code>## month day year birth1
## 1 12 1 1988 596934000</code></pre>
<p>Now let’s see what happens in this other example here:</p>
<pre class="r"><code>mother2 <- as.data.frame(list(month=2, day=30, year=1988))
mother2$birth1 <- as.POSIXct(paste0(as.character(mother2$year),
"-", as.character(mother2$month),
"-", as.character(mother2$day)),
origin="1970-01-01")</code></pre>
<p>This is what happens:</p>
<pre><code>Error in as.POSIXlt.character(x, tz, ...) :
character string is not in a standard unambiguous format</code></pre>
<p>This error is to be expected; there is no 30th of February! It turns out that in some rare cases, weird dates like this exist in my data. Probably some encoding errors. Not a problem I thought, I could use <code>tryCatch</code> and return <code>NA</code> in the case of an error.</p>
<pre class="r"><code>mother2 <- as.data.frame(list(month=2, day=30, year=1988))
mother2$birth1 <- tryCatch(as.POSIXct(paste0(as.character(mother2$year),
"-", as.character(mother2$month),
"-", as.character(mother2$day)),
origin="1970-01-01"), error=function(e) NA)
print(mother2)</code></pre>
<pre><code>## month day year birth1
## 1 2 30 1988 NA</code></pre>
<p>Pretty great, right? Well, no. Take a look at what happens in this case:</p>
<pre class="r"><code>mother <- as.data.frame(list(month=c(12, 2), day=c(1, 30), year=c(1988, 1987)))
print(mother)</code></pre>
<pre><code>## month day year
## 1 12 1 1988
## 2 2 30 1987</code></pre>
<p>We’d expect to have a correct date for the first mother and an <code>NA</code> for the second. However, this is what happens</p>
<pre class="r"><code>mother$birth1 <- tryCatch(as.POSIXct(paste0(as.character(mother$year),
"-", as.character(mother$month),
"-", as.character(mother$day)),
origin="1970-01-01"), error=function(e) NA)
print(mother)</code></pre>
<pre><code>## month day year birth1
## 1 12 1 1988 NA
## 2 2 30 1987 NA</code></pre>
<p>As you can see, we now have an <code>NA</code> for both mothers! That’s actually to be expected. Indeed, this little example illustrates it well:</p>
<pre class="r"><code>sqrt(c(4, 9, "haha"))</code></pre>
<pre><code>Error in sqrt(c(4, 9, "haha")) :
non-numeric argument to mathematical function</code></pre>
<p>But you’d like to have this:</p>
<pre><code>[1] 2 3 NA</code></pre>
<p>So you could make the same mistake as myself and use tryCatch:</p>
<pre class="r"><code>tryCatch(sqrt(c(4, 9, "haha")), error=function(e) NA)</code></pre>
<pre><code>## [1] NA</code></pre>
<p>But you only get <code>NA</code> in return. That’s actually completely normal, but it took me off-guard and I spent quite some time to figure out what was happening. Especially because I had written unit tests to test my function <code>create_birthdays()</code> that was doing the above computations and all tests were passing! The problem was that in my tests, I only had a single individual, so for a wrong date, having <code>NA</code> for this individual was expected behaviour. But in a panel, only some individuals have a weird date like the 30th of February, but because of those, the whole column was filled with <code>NA</code>’s! What I’m doing now is trying to either remove these weird birthdays (there are mothers whose children were born on the 99-99-9999. Documentation is lacking, but this probably means <code>missing value</code>), or tyring to figure out how to only get <code>NA</code>’s for the “weird” dates. I guess that the answer lies with <code>dplyr</code>’s <code>group_by()</code> and <code>mutate()</code> to compute this birthdays for each individual separately.</p>
Unit testing with R2016-03-31T00:00:00+00:00http://b-rodrigues.github.com/2016/03/31/unit-testing-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've been introduced to unit testing while working with colleagues on quite a big project for which
we use Python.</p>
<p>At first I was a bit skeptical about the need of writing unit tests, but now I must admit that I
am seduced by the idea and by the huge time savings it allows. Naturally, I was wondering if the
same could be achieved with R, and was quite happy to find out that it also possible to write unit
tests in R using a package called <code>testthat</code>.</p>
<p>Unit tests (Not to be confused with unit root tests for time series) are small functions that test
your code and help you make sure everything is alright. I'm going to show how the <code>testthat</code>
packages works with a very trivial example, that might not do justice to the idea of
unit testing. But you'll hopefully see why writing unit tests is not a waste of your time,
especially if your project gets very complex (if you're writing a package for example).</p>
<p>First, you'll need to download and install <code>testthat</code>. Some dependencies will also be installed.</p>
<p>Now, you'll need a function to test. Let's suppose you've written a function that returns the
nth Fibonacci number:</p>
<pre><code class="r">Fibonacci <- function(n){
a <- 0
b <- 1
for (i in 1:n){
temp <- b
b <- a
a <- a + temp
}
return(a)
}
</code></pre>
<p>You then save this function in a file, let's call it <code>fibo.R</code>. What you'll probably do once you've
written this function, is to try it out:</p>
<pre><code class="r">Fibonacci(5)
</code></pre>
<pre><code>## [1] 5
</code></pre>
<p>You'll see that the function returns the right result and continue programming. The idea behind
unit testing is write a bunch of functions that you can run after you make changes to your code,
just to check that everything is still running as it should.</p>
<p>Let's create a script called <code>test_fibo.R</code> and write the following code in it:</p>
<pre><code class="r">test_that("Test Fibo(15)",{
phi <- (1 + sqrt(5))/2
psi <- (1 - sqrt(5))/2
expect_equal(Fibonacci(15), (phi**15 - psi**15)/sqrt(5))
})
</code></pre>
<p>The code above uses Binet's formula, a closed form formula that gives the nth Fibonacci number and compares it
our implementation of the algorithm. If you didn't know about Binet's formula, you could simply compute some numbers
by hand and compare them to what your function returns, for example. The function <code>expect_equal</code> is a function from the
package <code>testthat</code> and does exactly what it tells. We expect the result of our implementation to be equal to the result of
Binet's Formula. The file <code>test_fibo.R</code> can contain as many tests as you need.
Also, the file that contains the tests must start with the string <code>test</code>, so that <code>testthat</code> knows with files it has to run.</p>
<p>Now, we're almost done, create yet another script, let's call it <code>run_tests.R</code> and write the following code in it:</p>
<pre><code class="r">library(testthat)
source("path/to/fibo.R")
test_results <- test_dir("path/to/tests", reporter="summary")
</code></pre>
<p>After running these lines, and if everything goes well, you should see a message like this:</p>
<pre><code>> library(testthat)
> source("path/to/fibo.R")
> test_results <- test_dir("path/to/tests", reporter="summary")
.
Your tests are dandy!
</code></pre>
<p>Notice the small <code>.</code> over the message? This means that one test was run successfully. You'll get one dot per successful
test. If you take a look at <code>test_results</code> you'll see this:</p>
<pre><code>> test_results
file context test nb failed skipped error user system real
1 test_fibo.R Test Fibo(15) 1 0 FALSE FALSE 0.004 0 0.006
</code></pre>
<p>You'll see each file and each function inside the files that were tested, and also whether the test was skipped, failed
etc. This may seem overkill for such a simple function, but imagine that you write dozens of functions that get more
and more complex over time. You might have to change a lot of lines because as time goes by you add new functionality,
but don't want to break what was working. Running your unit tests each time you make changes can help you pinpoint
regressions in your code. Unit tests can also help you start with your code. It can happen that sometimes you don't
know exactly how to start; well you could start by writing a unit test that returns the result you want to have and
then try to write the code to make that unit test pass. This is called test-driven development.</p>
<p>I hope that this post motivated you to write unit tests and make you a better R programmer!</p>
</body>
Bootstrapping 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" /></a>
</div>
<p>Just as in the book, we find that the DiD estimate is not significant to the 5% level.</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 class="highlighter-rouge">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 class="highlighter-rouge">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 <a href="https://cloud.openmailbox.org/index.php/s/ghZwBxMb24tWGSL">here</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>