[R] How to create a proper S4 class?

Leonard Mada |eo@m@d@ @end|ng |rom @yon|c@eu
Wed Nov 17 05:33:22 CET 2021


Dear List-Members,


I want to create an S4 class with 2 data slots, as well as a plot and a 
line method.


Unfortunately I lack any experience with S4 classes. I have put together 
some working code - but I presume that it is not the best way to do it. 
The actual code is also available on Github (see below).


1.) S4 class
- should contain 2 data slots:
Slot 1: the agents:
  = agentMatrix class (defined externally, NetlogoR S4 class);
Slot 2: the path traveled by the agents:
   = a data frame: (x, y, id);
  - my current code: defines only the agents ("t");
setClass("agentsWithPath", contains = c(t="agentMatrix"));

1.b.) Attribute with colors specific for each agent
- should be probably an attribute attached to the agentMatrix and not a 
proper data slot;
Note:
- it is currently an attribute on the path data.frame, but I will 
probably change this once I get the S4 class properly implemented;
- the agentMatrix does NOT store the colors (which are stored in another 
class - but it is useful to have this information available with the 
agents);

2.) plot & line methods for this class
plot.agentsWithPath;
lines.agentsWithPath;


I somehow got stuck with the S4 class definition. Though it may be a 
good opportunity to learn about S4 classes (and it is probably better 
suited as an S4 class than polynomials).


The GitHub code draws the agents, but was somehow hacked together. For 
anyone interested:

https://github.com/discoleo/R/blob/master/Stat/ABM.Models.Particles.R


Many thanks,


Leonard



More information about the R-help mailing list