<p><div><div><div><div data-width="100" data-show-faces="false" data-send="true" data-layout="button_count" data-height="21" data-href="http://www.r-bloggers.com/careful-with-trycatch/"></div></div><div><a data-url="http://www.r-bloggers.com/careful-with-trycatch/" data-counturl="http://www.r-bloggers.com/careful-with-trycatch/" data-count="horizontal" data-text="Careful with tryCatch" class="twitter-share-button" data-via="rbloggers" href="https://twitter.com/share"></a></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="http://b-rodrigues.github.com/2016/06/21/careful-with-trycatch"> Econometrics and Free Software</a></strong>, and kindly contributed to <a rel="nofollow" href="http://www.r-bloggers.com/">R-bloggers)</a> </div>
<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><code>sqrt(&quot;a&quot;)
Error in sqrt(&quot;a&quot;) : 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><code>tryCatch(sqrt(&quot;a&quot;), error=function(e) print(&quot;You can't take the square root of a character, silly!&quot;))</code></pre>
<pre><code>## [1] &quot;You can't take the square root of a character, silly!&quot;</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><code>mother &lt;- 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><code>mother$birth1 &lt;- as.POSIXct(paste0(as.character(mother$year), 
                                   &quot;-&quot;, as.character(mother$month), 
                                   &quot;-&quot;, as.character(mother$day)), 
                            origin=&quot;1970-01-01&quot;)</code></pre>
<p>and to convert it to unix time:</p>
<pre><code>mother$birth1 &lt;- as.numeric(as.POSIXct(paste0(as.character(mother$year), 
                                              &quot;-&quot;, as.character(mother$month), 
                                              &quot;-&quot;, as.character(mother$day)),
                                       origin=&quot;1970-01-01&quot;))

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><code>mother2 &lt;- as.data.frame(list(month=2, day=30, year=1988))

mother2$birth1 &lt;- as.POSIXct(paste0(as.character(mother2$year), 
                                    &quot;-&quot;, as.character(mother2$month), 
                                    &quot;-&quot;, as.character(mother2$day)), 
                             origin=&quot;1970-01-01&quot;)</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><code>mother2 &lt;- as.data.frame(list(month=2, day=30, year=1988))

mother2$birth1 &lt;- tryCatch(as.POSIXct(paste0(as.character(mother2$year), 
                                    &quot;-&quot;, as.character(mother2$month), 
                                    &quot;-&quot;, as.character(mother2$day)), 
                             origin=&quot;1970-01-01&quot;), 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><code>mother &lt;- 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><code>mother$birth1 &lt;- tryCatch(as.POSIXct(paste0(as.character(mother$year), 
                                    &quot;-&quot;, as.character(mother$month), 
                                    &quot;-&quot;, as.character(mother$day)), 
                             origin=&quot;1970-01-01&quot;), 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><code>sqrt(c(4, 9, &quot;haha&quot;))</code></pre>
<pre><code>Error in sqrt(c(4, 9, &quot;haha&quot;)) : 
  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><code>tryCatch(sqrt(c(4, 9, &quot;haha&quot;)), 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>
<p><div><div><div><div data-width="55" data-show-faces="false" data-send="true" data-layout="box_count" data-height="62" data-href="http://www.r-bloggers.com/careful-with-trycatch/"></div></div><div><a data-url="http://www.r-bloggers.com/careful-with-trycatch/" data-counturl="http://www.r-bloggers.com/careful-with-trycatch/" data-count="vertical" data-text="Careful with tryCatch" class="twitter-share-button" data-via="rbloggers" href="https://twitter.com/share"></a></div><div></div></div><div></div></div>
<div>
<div>To <strong>leave a comment</strong> for the author, please follow the link and comment on their blog: <strong><a href="http://b-rodrigues.github.com/2016/06/21/careful-with-trycatch"> Econometrics and Free Software</a></strong>.</div>
<hr>
<a rel="nofollow" href="http://www.r-bloggers.com/">R-bloggers.com</a> offers <strong><a rel="nofollow" href="http://feedburner.google.com/fb/a/mailverify?uri=RBloggers">daily e-mail updates</a></strong> about <a title="The R Project for Statistical Computing" rel="nofollow" href="http://www.r-project.org/">R</a> news and <a title="R tutorials" rel="nofollow" href="http://www.r-bloggers.com/?s=tutorial">tutorials</a> on topics such as: <a title="Data science" rel="nofollow" href="http://www.r-bloggers.com/?s=data%20science">Data science</a>, <a title="Big Data" rel="nofollow" href="http://www.r-bloggers.com/?s=Big%20Data">Big Data, <a title="R jobs" rel="nofollow" href="http://www.r-users.com/">R jobs</a>, visualization (<a title="ggplot and ggplot2 tutorials" rel="nofollow" href="http://www.r-bloggers.com/?s=ggplot2">ggplot2</a>, <a title="Boxplots using lattice and ggplot2 tutorials" rel="nofollow" href="http://www.r-bloggers.com/?s=boxplot">Boxplots</a>, <a title="Maps and gis" rel="nofollow" href="http://www.r-bloggers.com/?s=map">maps</a>, <a title="Animation in R" rel="nofollow" href="http://www.r-bloggers.com/?s=animation">animation</a>), programming (<a title="RStudio IDE for R" rel="nofollow" href="http://www.r-bloggers.com/?s=RStudio">RStudio</a>, <a title="Sweave and literate programming" rel="nofollow" href="http://www.r-bloggers.com/?s=sweave">Sweave</a>, <a title="LaTeX in R" rel="nofollow" href="http://www.r-bloggers.com/?s=LaTeX">LaTeX</a>, <a title="SQL and databases" rel="nofollow" href="http://www.r-bloggers.com/?s=SQL">SQL</a>, <a title="Eclipse IDE for R" rel="nofollow" href="http://www.r-bloggers.com/?s=eclipse">Eclipse</a>, <a title="git and github, Version Control System" rel="nofollow" href="http://www.r-bloggers.com/?s=git">git</a>, <a title="Large data in R using Hadoop" rel="nofollow" href="http://www.r-bloggers.com/?s=hadoop">hadoop</a>, <a title="Web Scraping of google, facebook, yahoo, twitter and more using R" rel="nofollow" href="http://www.r-bloggers.com/?s=Web+Scraping">Web Scraping</a>) statistics (<a title="Regressions and ANOVA analysis tutorials" rel="nofollow" href="http://www.r-bloggers.com/?s=regression">regression</a>, <a title="principal component analysis tutorial" rel="nofollow" href="http://www.r-bloggers.com/?s=PCA">PCA</a>, <a title="Time series" rel="nofollow" href="http://www.r-bloggers.com/?s=time+series">time series</a>, <a title="finance trading" rel="nofollow" href="http://www.r-bloggers.com/?s=trading">trading</a>) and more...
<img height="1" alt="" width="1" src="http://feeds.feedburner.com/~r/RBloggers/~4/zslQqZFtZNE"></a></div>