<p><div><div><div><div data-show-faces="false" data-height="21" data-width="100" data-layout="button_count" data-send="true" data-href="https://www.r-bloggers.com/dealing-with-s3-methods-in-r-with-a-simple-example/"></div></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="https://insightr.wordpress.com/2017/07/11/dealing-with-s3-methods-in-r-with-a-simple-example/"> R – insightR</a></strong>, and kindly contributed to <a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers)</a> </div>
<p><strong>By Gabriel Vasconcelos</strong></p>
<h2>S3 objects</h2>
<p><code>R</code> has three object systems: S3, S4 and RC. S3 is by far the easiest to work with and it can make you codes much understandable and organized, especially if you are working on a package. The idea is very simple. First we must define a class to some object in <code>R</code> and then we define methods (functions) for this class based on generic functions that you may create or use the ones available.</p>
<p><span></span></p>
<h3>Step 1: Defining the object’s class</h3>
<p>The function below runs a linear regression and estimate the relevant statistics. Note that in the function I generate several objects and in the end I put them all in a list. Finally, I define the attribute class for my list.</p>
<pre>regression=function(x,y){
  x=cbind(1,x)
  beta=solve(t(x)%*%x)%*%t(x)%*%y
  residuals=y-x%*%beta
  fitted.values=x%*%beta
  sigmae=(t(residuals)%*%residuals)/(nrow(x)-ncol(x))
  stde=sqrt(diag(c(sigmae)*solve(t(x)%*%x)))
  tstat=beta/stde
  pvalue=2*pt(-abs(tstat),df=nrow(x)-ncol(x))
  res=list(coefficients=beta,residuals=residuals,fitted.values=fitted.values,
           stde=stde,tstat=tstat,pvalue=pvalue,y=y)
  class(res)=&quot;regression&quot; # Class definition
  return(res)
}
</pre>
<p>Now let’s use the function in some data and see what happens. If I ask <code>R</code> for the class of the resulting object it gives me the defined class “regression”. Additionally, there are some cool stuff you can do that has nothing to do with the class but with the way I defined the list <code>res</code>. If you type <code>coef(res)</code>, <code>residuals(res)</code> or <code>fitted(res)</code> you will get coefficients, residuals and fitted values. This will happen every time you name the objects in the list in the way I just did.</p>
<pre>set.seed(123)
x=matrix(rnorm(10*100),100,10)
colnames(x)=1:10
y=x%*%rep(1,ncol(x))+rnorm(100)
test=regression(x,y)
class(test) # check the class
</pre>
<pre>## [1] &quot;regression&quot;
</pre>
<h3>Step 2: Defining methods for “regression”“ class</h3>
<p>If you look at the documentation in some functions you will read “S3 method for class ‘XXX’”. Try <code>?summary.lm</code> for example. <code>summary</code> is a generic function that will define which method to call. The <code>.lm</code> tells <code>R</code> that the method to be called in this case is the one defined for the class lm.</p>
<p>To define our own method we just need to create a function using <code>generic.class</code>. However, the defined function must have all arguments in the generic function in the same order. For example, <code>summary</code> takes the argument “object” and the argument “…”. Your function must have the same two arguments in the same order plus the extra arguments you need. There are some exceptions. The function <code>plot</code> takes “x”, “y” and “…” but you may write your plot method without the argument “y”.</p>
<p>In the code below I defined a plot and a summary method for the class “regression”.</p>
<pre>plot.regression=function(x,...){
  plot(x$y,main=&quot;Fitted x Observed&quot;,type=&quot;l&quot;)
  lines(fitted(x),col=2)
}

summary.regression=function(object,digits=4,...){
  tab=cbind(coef(object),object$stde,object$tstat,object$pvalue)
  colnames(tab)=c(&quot;coef&quot;,&quot;stde&quot;,&quot;t&quot;,&quot;p&quot;)
  rownames(tab)=rownames(coef(object))
  rownames(tab)[1]=&quot;Cons.&quot;
  print(tab,digits=digits)
}
</pre>
<p>Now we can call your functions using only their generic name and <code>R</code> will automatically identify the right method to use.</p>
<pre>summary(test,3)
</pre>
<pre>##        coef  stde     t        p
## Cons. 0.137 0.109  1.25 2.14e-01
## 1     1.065 0.120  8.87 6.94e-14
## 2     0.996 0.112  8.88 6.73e-14
## 3     0.853 0.112  7.61 2.67e-11
## 4     1.138 0.109 10.47 3.37e-17
## 5     1.070 0.113  9.45 4.37e-15
## 6     0.963 0.118  8.17 1.92e-12
## 7     1.093 0.104 10.55 2.35e-17
## 8     1.110 0.110 10.12 1.82e-16
## 9     0.951 0.103  9.27 1.03e-14
## 10    1.137 0.106 10.69 1.20e-17
</pre>
<pre>plot(test)
</pre>
<p><img alt="plot of chunk unnamed-chunk-4" src="https://i2.wp.com/i.imgur.com/x2CaM55.png"></p>
<h3>Final Remarks</h3>
<p>As you can see, S3 objects are very easy to deal with. You can also define multiple classes to an object. If you are writing a package you have to be careful to export the functions in the right way. Fortunately, the RStudio tool for packages combined with the roxygen2 package does most of the job for you. You can identify generic functions reading the description in their documentation.</p>
<p> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/insightr.wordpress.com/467/" target="_blank"><img border="0" alt="" src="http://feeds.wordpress.com/1.0/comments/insightr.wordpress.com/467/"></a> <img border="0" alt="" src="https://i1.wp.com/pixel.wp.com/b.gif?resize=1%2C1&ssl=1" data-recalc-dims="1"></p>
	<p>
<div>
<div>To <strong>leave a comment</strong> for the author, please follow the link and comment on their blog: <strong><a href="https://insightr.wordpress.com/2017/07/11/dealing-with-s3-methods-in-r-with-a-simple-example/"> R – insightR</a></strong>.</div>
<hr>
<a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers.com</a> offers <strong><a rel="nofollow" href="https://feedburner.google.com/fb/a/mailverify?uri=RBloggers">daily e-mail updates</a></strong> about <a rel="nofollow" href="https://www.r-project.org/" title="The R Project for Statistical Computing">R</a> news and <a rel="nofollow" href="https://www.r-bloggers.com/search/tutorial" title="R tutorials">tutorials</a> on topics such as: <a rel="nofollow" href="https://www.r-bloggers.com/search/data%20science" title="Data science">Data science</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/Big%20Data" title="Big Data">Big Data, <a rel="nofollow" href="https://www.r-users.com/" title="R jobs">R jobs</a>, visualization (<a rel="nofollow" href="https://www.r-bloggers.com/search/ggplot2" title="ggplot and ggplot2 tutorials">ggplot2</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/boxplot" title="Boxplots using lattice and ggplot2 tutorials">Boxplots</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/map" title="Maps and gis">maps</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/animation" title="Animation in R">animation</a>), programming (<a rel="nofollow" href="https://www.r-bloggers.com/search/RStudio" title="RStudio IDE for R">RStudio</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/sweave" title="Sweave and literate programming">Sweave</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/LaTeX" title="LaTeX in R">LaTeX</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/SQL" title="SQL and databases">SQL</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/eclipse" title="Eclipse IDE for R">Eclipse</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/git" title="git and github, Version Control System">git</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/hadoop" title="Large data in R using Hadoop">hadoop</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/Web+Scraping" title="Web Scraping of google, facebook, yahoo, twitter and more using R">Web Scraping</a>) statistics (<a rel="nofollow" href="https://www.r-bloggers.com/search/regression" title="Regressions and ANOVA analysis tutorials">regression</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/PCA" title="principal component analysis tutorial">PCA</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/time+series" title="Time series">time series</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/trading" title="finance trading">trading</a>) and more...
<img width="1" alt="" src="http://feeds.feedburner.com/~r/RBloggers/~4/Mp6dYPX1JuE" height="1"></a></div>